Formatting a Range


Formatting contributes much to the usability of a worksheet. Borders and background colors can emphasize parts of a report, and conditional formatting can highlight exceptions within a range. Cell formatting can be combined into cell styles to make the same formatting combinations easy to reuse.

Add Borders to a Range

Borders help to demarcate regions with a block of cells. Sometimes you want to put borders around every cell within a range. Sometimes you want to put a single border around an entire range of cells. Sometimes you want a different border along one side of a range. A Range object has methods and properties to allow you to completely control whatever type of border you need.

  1. In Excel, make a copy of the RevenueFormulas worksheet. In the Visual Basic editor, copy the TestRange macro, give the new one the name AddBorders, and press F8 twice to initialize the myRange variable.

    Troubleshooting 

    If you don’t have a TestRange macro, see the first two steps of the “Refer to a Relative Range” section earlier in this chapter.

  2. In the Immediate window, type Set myRange = Range("B2").CurrentRegion and press Enter to assign the range containing the revenue calculations to the variable.

  3. In the Immediate window, type myRange.Borders.LineStyle =.

    As you type each period in the statement, an Auto List displays the available members. After you type the equal sign, no Auto List appears, but you can use the Object Browser to find the available options.

  4. In the Object Browser, in the Search Text box above the Classes list, type LineStyle, and click the Search button.

    image from book
    Search

  5. In the Search Results pane that appears, select XlLineStyle in the Class list.

    The Member list shows all the possible constants you can use for the LineStyle property.

    image from book

    XlLineStyle is not really a class, even though it shows up in the list of classes in the Object Browser. There is no such thing as an XlLineStyle object. It is, rather, an enumerated list. An enumerated list is used when a property or argument can accept only certain values. An enumerated list allows the object model designer to give each of those values a special name-for example, xlContinuous. Enumerated lists are included in the list of Classes, but with a special icon.

  6. In the Immediate window, type xlContinuous to finish the statement, and then press Enter.

    This adds a continuous border around each cell in the range. When you assign a value to the LineStyle property of the Borders object, the property changes for the border of each cell in the entire range.

    image from book

  7. In the Immediate window, type myRange.Borders.LineStyle = xlNone and press Enter to remove the borders.

    The value xlNone does not appear in the enumeration list for LineStyle because it is a global constant that is used by many Excel objects. You can search for it in the Object Browser if you want to see the complete list of global contants.

    The Borders object is actually a collection, and you can select specific borders within that collection. In principle, you could change cell borders one at a time, but because putting a border around an entire range is a common operation, there is a special method just for doing that.

  8. In the Immediate window, type myRange.BorderAround Weight:=xlThick and press Enter.

    This changes the edges of the range to a thick border. Because Weight is not the first argument, you have to type its name if you leave out LineStyle. Setting the border weight to Thick implies that the line will be continuous.

    image from book

    Suppose that you want a border on the right side of the quantities. To specify a single border, you can use an enumerated name in conjunction with the Borders collection. Auto Lists can help you with the syntax, but you have to be a little tricky.

  9. In the Immediate Window, type

    myRange.Borders(xlEdgeRight).LineStyle = xlContinuous, but do not press Enter. Immediately after myRange, type a period ( . ), type Columns(1), and then press Enter.

    Once you use the Columns property in a statement, you don’t see any more Auto Lists, but if you temporarily leave out the Columns property, you get Auto Lists for everything else except the line style. Then, after you get the syntax correct for the statement, you can go back and add the Columns property.

    image from book

  10. In the Immediate window, type

    myRange.Rows(2).Borders(xlEdgeBottom).LineStyle = xlContinuous and press Enter. This adds a border under the row of prices.

  11. Press F5 to end the macro. Copy the statements from the Immediate window into the AddBorders macro, and delete the two statements that fill and remove all the borders.

The finished macro should look like this:

Sub SetBorders()   Dim myRange As Range   Set myRange = Range("B2").CurrentRegion   myRange.BorderAround Weight:=xlThick   myRange.Columns(1).Borders(xlEdgeRight).LineStyle = xlContinuous   myRange.Rows(2).Borders(xlEdgeBottom).LineStyle = xlContinuous  End Sub

  1. Create a new copy of RevenueFormulas and test the finished macro.

Borders can emphasize parts of a report. The Borders collection allows you to change all the borders at one time or choose a particular type of border to modify. The BorderAround method is a convenient shortcut for assigning a border to all the edges of a multicell range.

Format the Interior of a Range

To enhance the readability of a worksheet, you might want to apply different background colors to various parts. For example, you might apply one format to all the cells that contain values that a user can input, and a different format to all cells that contain formulas.

  1. In Excel, create another copy of the RevenueFormulas worksheet. In Visual Basic, copy the TestRange macro, name the new one AddColors, and press F8 twice to initialize the myRange variable.

    Troubleshooting 

    If you don’t have a TestRange macro, see the first two steps of the “Refer to a Relative Range” section earlier in this chapter.

  2. In the Immediate window, type Set myRange = Range("B2").CurrentRegion and press Enter to assign the range containing the revenue calculations to the variable.

  3. In the Immediate window, type myRange.Interior.Color =.

    As you type each period in the statement, an Auto List displays the available members. After you type the equal sign, however, no Auto List appears. For the Color property, there is no enumerated list. You can enter any number between 0 (which equals black) and 16777215 (which equals white), so there are literally more than 16 million possible values. This is a major change from previous versions of Excel, where colors in a worksheet were limited to a palette of only 56 colors.

    Colors on a computer correspond to the red, green, and blue guns of a cathode ray tube. (Liquid crystal displays use a different technology, but the same component colors.) Visual Basic has an RGB function you can use to specify precise red, green, and blue components, but Excel provides an easier way to specify the color you want: it includes an enumerated list that gives meaningful names to about 140 of the most common colors.

    See Also 

    Excel 2007 also uses theme colors to help you use predefined sets of compatible colors. Theme colors are described in more detail in the section titled “Add a Gradient Fill to a Cell” in Chapter 6, “Explore Graphical Objects.”

  4. In the Immediate window, type rgbMediumVioletRed to complete the statement, and press Enter. (Once you get past rgbM, press Ctrl+Space to get to the middle of the rgb color values.)

    The background color of the entire range changes to a medium violet red.

    image from book

    Now that Excel can handle millions of colors, it has a new capability to change how light (the tint) or dark (the shade) a color is without changing the actual color (the hue).

  5. In the Immediate window, type myRange.Interior.TintAndShade = -0.2 and press Enter. The color changes to a slightly darker shade of violet red.

    A range object has a special method called SpecialCells that isolates cells within the range based on various attributes. For example, you can reference all the formula cells within the range.

  6. In the Immediate window, type myRange.SpecialCells(xlCellTypeFormulas).Interior.TintAndShade = 0.3 and press Enter.

    The block of formulas changes to a lighter tint of violet red. In this range, the formulas form a contiguous block, but SpecialCells can return a range of discontiguous cells as well.

    image from book

    In Excel, you can give a name to a set of formatting characteristics. This is called a cell style. There are several built-in styles in a workbook. One of them is named Input, so that you can use it to format cells that can accept user input-typically cells that contain constants that are numbers.

  7. In the Immediate window, type

    myRange.SpecialCells(xlCellTypeConstants, xlNumbers).Style = "Input" and press Enter.

    The cells with prices and quantities change to a light tan, with borders around each cell. The constant xlNumbers doesn’t appear in an Auto List, but you can find the list in the Object Browser by searching for SpecialCells.

    image from book

    You can modify the style format in the same way that you can modify a range format directly.

  8. Enter the following two statements in the Immediate window:

    ActiveWorkbook.Styles("Input").Interior.Color = rgbMediumVioletRed ActiveWorkbook.Styles("Input").Interior.TintAndShade = 0.5 

    This changes the Input style so that it has a lighter version of the same violet red shade as the rest of the cells. When applying a style to cells that can take input values, you may want to search the entire worksheet for the numeric constants. To do that, you just start with the global Cells property.

  9. In the Immediate window, type

    Cells.SpecialCells(xlCellTypeConstants, xlNumbers).Style = "Input" and press Enter.

    This adds the Input style to the Discount cell value. If you had hundreds of input cells scattered all over the worksheet, this statement would still find them all. The text labels in the Revenue range are hard to read, with the black text on a dark background. You can use SpecialCells to isolate all the cells that contain text constants.

  10. In the Immediate window, type myRange.SpecialCells(xlCellTypeConstants, xlTextValues).Font.Color = rgbWhite and press Enter.

    This changes the font color for the labels to white, but they would look better bold as well. In fact, all the constants within the formula range would look better if they were bold.

  11. In the Immediate window, type

    myRange.SpecialCells(xlCellTypeConstants).Font.Bold = True and press Enter.

    This changes all the constants within the range store in myRange to bold. By leaving out the second argument to SpecialCells, you get everything that matches the general type. You can also use a special style to clear all the formatting.

    image from book

  12. In the Immediate window, type Cells.Style = "Normal" and press Enter.

    This clears all the formatting, including the number and formats. When you clear formats from a worksheet, what it really does is apply the Normal style to all the cells. By changing the Normal style, you change the default appearance of cells in the workbook.

    image from book

  13. Press F5 to end the macro. Copy the statements from the Immediate window into the AddColors macro, and delete the statement that clears all the formatting.

    The finished macro, ignoring optional line breaks, should look like this:

    Sub SetColors()   Dim myRange As Range   Set myRange = Range("B2").CurrentRegion      myRange.Interior.Color = rgbMediumVioletRed   myRange.Interior.TintAndShade = -0.2   myRange.SpecialCells(xlCellTypeFormulas). _   Interior.TintAndShade = 0.3      myRange.SpecialCells(xlCellTypeConstants, xlNumbers). _   Style = "Input"   ActiveWorkbook.Styles("Input").Interior _   .Color = rgbMediumVioletRed   ActiveWorkbook.Styles("Input").Interior _   .TintAndShade = 0.5   Cells.SpecialCells(xlCellTypeConstants, xlNumbers) _   .Style = "Input"      myRange.SpecialCells(xlCellTypeConstants, xlTextValues) _   .Font.Color = rgbWhite   myRange.SpecialCells(xlCellTypeConstants).Font.Bold = True  End Sub

  14. Create a new copy of RevenueFormulas and test the finished macro.

Ranges are powerful objects. They are the essence of Excel. With ranges you can organize information, create formulas, and apply formatting. And you can do all of that with under the control of VBA macros.

CLOSE the Chapter04.xlsm workbook.



Microsoft Office Excel 2007 Visual Basic for Applications Step by Step
Microsoft Excel 2002 Visual Basic for Applications Step by Step (Step by Step (Microsoft))
ISBN: 0735613591
EAN: 2147483647
Year: 2004
Pages: 99
Authors: Reed Jacobsen

Similar book on Amazon
Excel 2003 Power Programming with VBA (Book & CD-ROM)
Excel 2003 Power Programming with VBA (Book & CD-ROM)
Microsoftu00ae Office Excelu00ae 2007 Visual Basicu00ae for Applications Step by Step (BPG-step by Step)
Microsoftu00ae Office Excelu00ae 2007 Visual Basicu00ae for Applications Step by Step (BPG-step by Step)
Excel 2003 Formulas
Excel 2003 Formulas
Writing Excel Macros with VBA, 2nd Edition
Writing Excel Macros with VBA, 2nd Edition

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net