Chapter 16. Working with Colors

In This Chapter

  • Specifying colors in VBA code

  • VBA conversion functions for various color models

  • Converting colors to grayscale

  • Working with Excel 2007 document themes

  • Modifying colors in Shape objects and charts

One of the most significant changes in Excel 2007 is the abandonment of the old 56–color workbook palette. This chapter describes how color is used in Excel 2007, including the new "themes." I include many examples that should help you understand how these changes affect your workbooks and charts. The chapter also contains VBA code that deals with colors.

About Excel 2007 Colors

Dealing with color in Excel 2007 is no trivial matter. I'm the first to admit that it can be complicated. And often, recording a macro while you change the color of a cell or object only adds to the confusion. In this chapter, I attempt to pull it all together.

Back in the pre–Excel 2007 days, a workbook stored a palette of 56 colors. These colors were the only ones available for cell backgrounds, cell text, and charts. Sure, you could modify any or all of those colors, but you couldn't exceed the 56–color limit for a workbook.

But things have changed. You now have access to a virtually unlimited number of colors in a workbook — actually, the limit is 16, 777, 216 colors, but that certainly qualifies as "virtually" unlimited as far as I'm concerned.

Specifying Colors

Using VBA, you specify a color as a numeric color value, which is a number between 0 and 16, 777, 215. For example, the VBA statement that follows changes the background color of the active cell to a dark maroon:

ActiveCell.Interior.Color = 5911168

In addition, VBA has some predefined constants for some common colors. For example, vbRed has a value of 255 (the value for pure red) and vbGreen has a value of 65, 280.

No one, of course, can keep track of nearly 17 million colors, and the predefined constants are limited. A better way to change a color is to specify the color in terms of its red, green, and blue components — the RGB color system.

The RGB Color System

The RGB color system combines various levels of three colors: red, green, and blue. Each of these component colors can range from 0 through 255. Therefore, the total number of possible colors is 256 × 256 × 256 = 16, 777, 216. When all three color components are 0, the color is pure black. When all three components are 255, the color is pure white. When all three are 128 (the half–way point), the color is medium gray. The remaining 16, 777, 213 possible combinations of these three values represent other colors.

To specify a color using the RGB system in VBA, use the RGB function. This function accepts three arguments that represent the red, green, and blue components of a color. The function returns a decimal color value.

Note

The numeric color values I've referred to aren't really a different color system. A decimal color value is simply the base 10 equivalent of an RGB color. For the color white, the RGB values of 255, 255, 255 are written as FF, FF, FF in base 16 (hexadecimal). The values are concatenated to get the base 16 color value FFFFFF, which in base 10, is written 16, 777, 215. For lack of a better term, I refer to these base 10 color value as decimal color values.

The statement that follows uses the RGB function to assign a color that's exactly the same as the one assigned in the preceding section (that dark maroon, 5911168):

ActiveCell.Interior.Color = RGB(128, 50, 90)

Table 16-1 shows the RGB components and the decimal color code of some common colors.

Table 16-1. COLOR EXAMPLES

Name

Red Component

Green Component

Blue Component

Color Value

Black

0

0

0

0

White

255

255

255

255

Red

255

0

0

255

Green

0

255

0

65280

Blue

0

0

255

16711680

Yellow

255

255

0

65535

Pink

255

0

255

16711935

Turquoise

0

255

255

16776960

Brown

153

51

0

13209

Indigo

51

51

153

10040115

80% Gray

51

51

51

3355443

The HSL Color System

If you select the More Colors option when choosing a color in Excel, you'll see the Colors dialog box. Click the Custom tab, and you can choose from two color models to specify your color: RGB and HSL. Figure 16-1 shows the Colors dialog box with the HSL color model selected.

In the HSL color system, colors are specified using three parameters: hue, saturation, and luminance. As with RGB colors, each of these parameters can range from 0 to 255. Each RGB color has an equivalent HSL color, and each HSL color has an equivalent RGB color value. In other words, any of the 16, 777, 216 colors can be specified by using either the HSL or RGB color system.

Note

Although the Colors dialog box lets you specify a color using the HSL color model, this is actually the only area in which Excel supports the HSL color model. For example, when you specify a color using VBA, it must be an RGB color value. You can either use the RGB function, or enter a decimal color value directly. However, VBA does not have a corresponding HSL function.

Choosing a color using the HSL color system.

Figure 16-1. Choosing a color using the HSL color system.

Converting Colors

If you know the three color component values, converting an RGB color to a decimal color value is easy. Just use VBA's RGB function. Assume three variables (r, g, and b), each of which represents a color component value between 0 and 255. To calculate the equivalent decimal color value, use a statement like this:

DecimalColor = RGB(r, g, b)

To perform this conversion in a worksheet formula, create this simple VBA function in a VBA module:

Function RGB2DECIMAL(R, G, B)
,    Converts from RGB to decimal color
     RGB2DECIMAL = RGB(R, G, B)
End Function

The following example worksheet formula assumes that the three color values are in A1:C1:

=RGB2DECIMAL(A1, B1,C1)

Converting a decimal color to its red, green, and blue components is not so simple. Here's a function that returns a three–element array:

Function DECIMAL2RGB(ColorVal) As Variant
'   Converts a color value to an RGB triplet
'   Returns a 3–element variant array
    DECIMAL2RGB = Array(ColorVal  256 ^ 0 And 255, _
ColorVal  256 ^ 1 And 255, ColorVal  256 ^ 2 And 255)
End Function

To use the DECIMAL2RGB function in a worksheet formula, the formula must be entered as a three–cell array formula. For example, assume that cell A1 contains a decimal color value. To convert that color value to its RGB components, select a three–cell horizontal range and then enter the following formula. Press Ctrl+Shift+Enter to make it an array formula, and don't enter the braces.

{=DECIMAL2RGB(A1)}

If the three–cell range is vertical, you need to transpose the array, as follows:

{=TRANSPOSE(DECIMAL2RGB(A1))}

Figure 16-2 shows the DECIMAL2RGB function in use in a worksheet.

The DECIMAL2RGB function converts a decimal color value to its red, green, and blue components.

Figure 16-2. The DECIMAL2RGB function converts a decimal color value to its red, green, and blue components.

Note

The companion CD–ROM contains a workbook with the following color conversion functions: DECIMAL2RGB, DECIMAL2HSL, HSL2RGB, RGB2DECIMAL, RGB2HSL, and HSL2DECIMAL. The file is named color conversion functions.xlsm.

Understanding Grayscale

When you create worksheets and charts, it's important to remember that not everyone has a color printer. And even if your chart is printed on a color printer, it might be photocopied or faxed.

When content is printed on a noncolor device, colors are converted to grayscale. Sometimes you'll be lucky and your colors will display nicely when converted to grayscale. Other times, you won't be so lucky. For example, the columns in a chart may be indistinguishable when the colors are converted.

Every grayscale color has an equal component of red, green, and blue. Pure black is RGB(0, 0, 0). Pure white is RGB(255, 255, 255). Neutral gray is RGB(128, 128, 128). Using this color system produces 256 shades of gray.

To create a 256–color grayscale gradient in a range of cells, execute the procedure that follows. It colors the background of cells in the range A1:A256, starting with black and ending with white. You might want to zoom out in the worksheet to see the entire range.

Sub GenerateGrayScale()
    Dim r As Long
    For r = 0 To 255
        Cells(r + 1, 1).Interior.Color = RGB(r, r, r)
    Next r
End Sub

Converting Colors to Gray

One approach to grayscale conversion is to simply average the red, green, and blue components of a color and use that single value for the red, green, and blue components of its grayscale equivalent. That approach, however, does not take into account the fact that different colors are perceived as varying levels of brightness. For example, green is perceived to be brighter than red, and red is perceived to be brighter than blue.

Perceptual experiments have arrived at the following "recipe" to convert an RGB color value to a grayscale value:

  • 28.7% of the red component

  • 58.9% of the green component

  • 11.4% of the blue component

For example, consider color value 16751001, a shade of violet that corresponds to RGB(153, 153, 255). Applying the factors listed above, the RGB values are as follows

  • Red: 28.7% × 153 = 44

  • Green: 58.9% × 153 = 90

  • Blue: 11.4% × 255 = 29

The sum of these values is 163. Therefore, the corresponding grayscale RGB value for color value 16751001 is RGB(163, 163, 163).

Following is a VBA function that accepts a decimal color value as its argument, and returns the corresponding grayscale decimal value:

Function Grayscale(color)
    Dim r As Long, g As Long, b As Long
    r = (color  256 ^ 0 And 255) * 0.287
    g = (color  256 ^ 1 And 255) * 0.589
    b = (color  256 ^ 2 And 255) * 0.114
    Grayscale = RGB(r + g + b, r + g + b, r + g + b)
End Function

Viewing Charts as Grayscale

Here's a technique that can let you see how an embedded chart looks when converted to grayscale:

  1. Select the chart.

  2. Press Ctrl+C to copy the chart to the Clipboard.

  3. Click a cell and choose Home

    Viewing Charts as Grayscale
  4. Select the picture and choose Picture Tools

    Viewing Charts as Grayscale

These steps are automated in the macro that follows. The ShowChartAsGrayScale procedure copies the active chart as a picture and converts the picture to grayscale. After you've determined whether the colors are satisfactory, you can delete the picture.

Sub ShowChartAsGrayScale()
'   Copies the active chart as a grayscale picture
'   Embedded charts only
    If ActiveChart Is Nothing Then
       MsgBox "Select a chart."
       Exit Sub
   End If
   ActiveChart.Parent.CopyPicture
ActiveChart.Parent.TopLeftCell.Select
   ActiveSheet.Pictures.Paste
   ActiveSheet.Pictures(ActiveSheet.Pictures.Count). _
     ShapeRange.PictureFormat.ColorType = msoPictureGrayscale
End Sub

Note

A workbook with this example is available on the companion CD–ROM. The filename is chart to grayscale picture.xlsm.

Experimenting with Colors

Figure 16-3 shows a workbook that I created that deals with colors. If you're at all confused about how the RGB color model works, spending some time with this color demo workbook can probably make it all very clear.

This workbook demonstrates how red, green, and blue colors combine.

Figure 16-3. This workbook demonstrates how red, green, and blue colors combine.

Note

This workbook, named RGB color demo.xlsm, is available on the companion CD–ROM.

This workbook contains three vertical scroll bars, each of which controls the background color of a range. Use these scroll bars to specify the red, green, and blue component for a color to values between 0 and 255. Moving the scroll bars changes several areas of the worksheet:

  • The cells above the scroll bars display the color components in hexadecimal (00-FF) format and in decimal (0-255) format. Hexadecimal RGB color values are often used in specifying colors for HTML documents.

  • The ranges next to each scroll bar change intensity, corresponding to the scroll bar's position (that is, the value of the color component).

  • A range below the scroll bars depicts the combined color, determined by the RGB values you specify.

  • A cell displays the decimal color value.

  • Another range depicts the color's approximate appearance when it is converted to grayscale.

  • A range of cells shows the corresponding HSL color values.

Understanding Document Themes

A significant new feature in Excel 2007 is document themes. With a single mouse click, the user can change the entire look of a document. A document theme consists of three components: colors, fonts, and effects (for graphic objects). The rationale for using themes is that they may help users produce better–looking and more consistent documents. A theme applies to the entire workbook, not just the active worksheet. In addition, the same themes are available in Word and PowerPoint, making it easy to create complimentary spreadsheets, documents, and presentations.

About Document Themes

Microsoft Office 2007 ships with 20 document themes, and additional themes can be added. The user interface Ribbon includes several style galleries (for example, the Chart Styles gallery). The styles available in these galleries vary depending on which theme is assigned to the document. And, if you apply a different theme to the document, the document changes to reflect the new theme's colors, fonts, and effects.

Note

If you haven't explored document themes, open the workbook named document theme demo.xlsx found on the companion CD–ROM. This workbook contains a range that shows each theme color, two shapes, text (using the headings and body fonts), and a chart. Choose Page Layout

About Document Themes

You can also mix and match theme elements. For example, you can use the colors from one theme, the fonts from another theme, and the effects from yet a different theme. In addition, the user can create a new color set or a new font set. These customized themes can be saved and then applied to other workbooks.

Note

The concept of document themes is based on the notion that users will apply little, if any, "nontheme" formatting to the document. If the user applies colors or fonts that aren't Part of the current theme, this formatting will not be modified if a new theme is applied to the document. Therefore, it's still very easy to create an ugly document with mismatched colors and too many different fonts.

Understanding Document Theme Colors

When you apply a color to a cell or object, the color is selected from a control like the one shown in Figure 16-4. The control displays the 60 theme colors (10 columns by 6 rows) plus 10 additional "standard" colors. Clicking the More Colors option displays the Color dialog box, in which the user can specify any of the 16, 777, 216 available colors.

A color–selection control.

Figure 16-4. A color–selection control.

The 60 theme colors are identified by pop–up ToolTips. For example, using the default Office theme, the color in the second row of the sixth column is known as Red, Accent 2, Lighter 80%. If you're using a different theme, the "Red" Part of the ToolTip is replaced by the actual color for that theme.

Table 16-2 shows all 60 theme colors. The first row shows the color name, and the other rows show the light/dark variation of that color. Examine the table, and you won't see much of a pattern — although the accent colors are consistent in terms of the dark/light variations.

Keep in mind that these color names remain the same, even if a different document theme is applied. The document theme colors actually consist of the 10 colors displayed in the top row, and each of these 10 colors has five dark/light variations.

Note

If you select Page Layout

A color–selection control.

You may find it enlightening to record a macro while you change the fill color and text color of a range. Unfortunately, recording your actions while you change the color of a chart element does not generate any code.

Following is a macro that I recorded when a range was selected. For the fill color, I chose "Background 2, Darker 50%," and for the text color, I chose "Text 2, Lighter 80%."

Sub Macro1()
    Range("A1:D13").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorDark2
        .TintAndShade = −0.499984740745262
        .PatternTintAndShade = 0
    End With
    With Selection.Font
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With
End Sub

Table 16-2. THEME COLOR NAMES

Row/Column

1

2

3

4

5

6

7

8

9

10

1

Background 1

Text 1

Background 2

Text 2

Accent 1

Accent 2

Accent 3

Accent 4

Accent 5

Accent 6

2

Darker 5%

Lighter 50%

Darker 10%

Lighter 80%

Lighter 80%

Lighter 80%

Lighter 80%

Lighter 80%

Lighter 80%

Lighter 80%

3

Darker 15%

Lighter 35%

Darker 25%

Lighter 60%

Lighter 60%

Lighter 60%

Lighter 60%

Lighter 60%

Lighter 60%

Lighter 60%

4

Darker 25%

Lighter 25%

Darker 50%

Lighter 40%

Lighter 40%

Lighter 40%

Lighter 40%

Lighter 40%

Lighter 40%

Lighter 40%

5

Darker 35%

Lighter 15%

Darker 75%

Darker 25%

Darker 25%

Darker 25%

Darker 25%

Darker 25%

Darker 25%

Darker 25%

6

Darker 50%

Lighter 5%

Darker 90%

Darker 50%

Darker 50%

Darker 50%

Darker 50%

Darker 50%

Darker 50%

Darker 50%

First of all, you can safely ignore the three pattern–related properties (Pattern, PatternColorIndex, and PatternTintAndShade) in the recorded macro. These properties refer to the ugly, old–fashioned (but still supported) cell patterns, which you can specify on the Fill tab of the Format Cells dialog box. These properties simply maintain any existing pattern that may exist in the range.

The recorded macro, after I delete the three pattern–related properties, is as follows:

Sub Macro1()
    Range("A1:D13").Select
    With Selection.Interior
         .ThemeColor = xlThemeColorDark2
         .TintAndShade = −0.499984740745262
    End With
    With Selection.Font
         .ThemeColor = xlThemeColorLight2
         .TintAndShade = 0.799981688894314
     End With
End Sub

As you can see, each color is specified in terms of a Theme Color property and a TintAndShade property. The ThemeColor property uses built–in constants. The value for these constants is simply the column number of the 10–×–6 theme color table. For example, xlThemeColorDark2 has a value of 3 because that color is in the third column of the theme color table. But what about the TintAndShade property?

The TintAndShade property can have a value between −1 and +1. A value of −1 results in black, and a value of +1 results in white. A TintAndShade property value of 0 gives the "pure" color. In other words, as the TintAndShade value goes negative, the color gets increasingly darker until it's pure black. As the TintAndShade value goes positive, the color gets increasingly lighter until it's pure white. Notice that the TintAndShade values in the recorded macro include many extra decimal places. The TintAndShade value of −0.499984740745262, for example, is equivalent to "Darker 50%."

To arrive at the TintAndShade property value that corresponds to a particular theme color variation, look back at Table 16-2.

Note

For a demonstration of how the TintAndShade property changes a color, open the tintandshade demo.xlsm workbook on the companion CD–ROM (see Figure 16-5). Specify a starting color, and the macro displays that color with 50 levels of the TintAndShade property values, ranging from −1 to +1. It also displays the decimal color value and the red, green, and blue components of the color (which are displayed in achart).

This workbook demonstrates how the TintAndShade property affects a color.

Figure 16-5. This workbook demonstrates how the TintAndShade property affects a color.

Displaying All Theme Colors

Using the information in Table 16-2, I wrote the following macro, which displays all 60 theme color variations in a range of cells:

Sub ShowThemeColors()
 Dim r As Long, c As Long
 For r = 1 To 6
   For c = 1 To 10
      With Cells(r, c).Interior
      .ThemeColor = c
      Select Case c
          Case 1 'Background 1
          Select Case r
              Case 1: .TintAndShade = 0
              Case 2: .TintAndShade = −0.05
              Case 3: .TintAndShade = −0.15
              Case 4: .TintAndShade = −0.25
              Case 5: .TintAndShade = −0.35
              Case 6: .TintAndShade = −0.5
End Select
      Case 2 'Text 1
          Select Case r
              Case 1: .TintAndShade = 0
              Case 2: .TintAndShade = 0.5
              Case 3: .TintAndShade = 0.35
              Case 4: .TintAndShade = 0.25
              Case 5: .TintAndShade = 0.15
              Case 6: .TintAndShade = 0.05
          End Select
      Case 3 'Background 2
          Select Case r
              Case 1: .TintAndShade = 0
              Case 2: .TintAndShade = −0.1
              Case 3: .TintAndShade = −0.25
              Case 4: .TintAndShade = −0.5
              Case 5: .TintAndShade = −0.75
              Case 6: .TintAndShade = −0.9
          End Select
      Case Else 'Text 2, and Accent 1-6
          Select Case r
              Case 1: .TintAndShade = 0
              Case 2: .TintAndShade = 0.8
              Case 3: .TintAndShade = 0.6
              Case 4: .TintAndShade = 0.4
              Case 5: .TintAndShade = −0.25
              Case 6: .TintAndShade = −0.5
          End Select
         End Select
        Cells(r, c) = .TintAndShade
         End With
     Next c
   Next r
End Sub

Figure 16-6 shows the result of executing the ShowThemeColors procedure. (It looks better in color.) If you change to a different document theme, the colors will be updated to reflect those in the new theme.

Note

This example, named generate theme colors.xlsm, is available on the companion CD–ROM.

A VBA macro generated these theme colors.

Figure 16-6. A VBA macro generated these theme colors.

So far in this chapter, I've described how to change the fill color of a range by setting the Color property of the Interior object. As I noted, using the VBA RGB function makes this easier. These two statements demonstrate how to change the fill color of a range (they both have the same result):

Range("A1:F24").Interior.Color = 5913728
Range("A1:F24").Interior.Color = RGB(128, 60, 90)

What if you'd like your code to change the background color of a range to a specific theme color, such as the color in the third row of the sixth column (the color identified as Accent 2, Lighter 60%)?

The Excel 2007 designers seemed to have forgotten to include a direct way to specify a theme color using this type of indexing. You might think that the ColorIndex property would do the job, but it doesn't. The ColorIndex property refers to colors in the (pre–Excel 2007) 56–color palette.

In actual practice, this omission is not a serious problem. When setting a color, the important property is the ThemeColor property, which ranges from 1 to 10. Your code can assign a value to the TintAndShade property to vary that color (a negative value for a darker variation and a positive value for a lighter variation). If the user applies a different document theme, the color will still change in a relative manner.

Note

If you modify the Interior.Color property of a cell to a color that corresponds to a theme color, the cell's color is not determined by the current theme. In other words, if you apply a new theme, the cell's color will not change. To change the color of a cell such that it varies with the theme, you must set the Interior.ThemeColor property.

Working with Shape Objects

This chapter has focused exclusively on modifying the color of a range. The following sections provide examples of changing colors in Shape objects. In Excel, use the Insert

Working with Shape Objects

Figure 16-7 shows a Shape object inserted in a worksheet. This object's default name is Right Arrow 1. The number in the name varies, depending on how many shapes you have inserted. For example, if you had previously inserted two other shapes (of any style), the name would be Right Arrow 3.

A Shape object in a worksheet.

Figure 16-7. A Shape object in a worksheet.

A Shape's Background Color

The background color of a Shape object is determined by the RGB property. So, to get the decimal color value of this shape, use a statement like this:

MsgBox ActiveSheet.Shapes("Right Arrow 1").Fill.ForeColor.RGB

This statement may be a bit confusing, so I'll break it down. The Fill property of the Shape object returns a FillFormat object. The ForeColor property of the FillFormat object returns a ColorFormat object. So the RGB property actually applies to the ColorFormat object, and this property contains the decimal color value.

Note

If you're confused about the use of the ForeColor property in this example, you're not alone. Most people, myself included, would expect to use the BackColor property of the FillFormat object to change the background color of an object. As it turns out, the BackColor property is used for the second color if the object is shaded or filled with a pattern. For an unfilled shape with no pattern, the ForeColor property controls the background color.

When working with Shape objects, you almost always want your code to perform multiple actions. Therefore, it's efficient to create an object variable. The code that follows creates an object variable named Shp:

Dim Shp As Shape
Set Shp = ActiveSheet.Shapes("Right Arrow 1")
MsgBox Shp.Fill.ForeColor.RGB

Tip

An additional advantage to creating an object variable is that you can take advantage of the VBE's Auto List Members feature, which displays the possible properties and objects as you type (see Figure 16-8). This is particularly helpful in the case of Shape objects because actions you take with shapes are not recorded by Excel's macro recorder.

Typing a statement with the assistance of the Auto List Members feature.

Figure 16-8. Typing a statement with the assistance of the Auto List Members feature.

If you'll be working only with the shape's colors, you can create an object variable for the shape's ColorFormat object, like this:

Dim ShpCF As ColorFormat
Set ShpCF = ActiveSheet.Shapes("Right Arrow 1").Fill.ForeColor
MsgBox ShpCF.RGB

The RGB property of the ColorFormat object controls the color of the shape. Following are some additional properties. If you're not familiar with document theme colors, see the "Understanding Document Themes" section, earlier in this chapter.

  • ObjectThemeColor: A number between 1 and 10 that represents the theme color (that is, a color in the first row of the 10–x–6 theme color grid)

  • SchemeColor: A number that ranges from 0 to 80 that represents the color as an index in the current color scheme. These are colors from the old 56–color palette, and I don't see any need to ever use the SchemeColor property.

  • TintAndShade: A number between −1 and +1 that represents the lightness or darkness of the theme color.

  • Type: A number that represents the ColorFormat object type. As far as I can tell, this read–only property is always 1, which represents the RGB color system.

To set the color of a shape to a theme color, use code like the following:

Dim Shp As Shape
Set Shp = ActiveSheet.Shapes("Right Arrow 1")
Shp.Fill.ForeColor.ObjectThemeColor = 3
Shp.Fill.ForeColor.TintAndShade = .25

Changing the fill color of a shape does not affect the shape's outline color. To modify the color of a shape's outline, access the ColorFormat object of the shape's LineFormat object. The following statements set a shape's fill color and outline to red:

Dim Shp As Shape
Set Shp = ActiveSheet.Shapes("Right Arrow 1")
Shp.Fill.ForeColor.RGB = RGB(255, 0, 0)
Shp.Line.ForeColor.RGB = RGB(255, 0, 0)

Here's an alternate way to accomplish the same effect, using object variables:

Dim Shp As Shape
Dim FillCF As ColorFormat
Dim LineCF As ColorFormat
Set Shp = ActiveSheet.Shapes("Right Arrow 1")
Set FillCF = Shp.Fill.ForeColor
Set LineCF = Shp.Line.ForeColor
FillCF.RGB = RGB(255, 0, 0)
LineCF.RGB = RGB(255, 0, 0)

Using Other Fill Types with a Shape

Shapes can also display other types of fills, such as gradients, pictures, and textures. The examples in this section demonstrate how to apply these other types of fills to a Shape object.

Note

All the examples in this section are available on the companion CD–ROM. The filename is shape object colors.xlsm.

The following code creates a rectangle, hides its border, and applies a two–color gradient. One of the colors is set specifically; the other color is one of the document theme colors. Figure 16-9 shows the result of running this macro.

A Shape object with a two–color gradient fill.

Figure 16-9. A Shape object with a two–color gradient fill.

Sub MakeShapeWithGradient()
    Dim Shp As Shape

'   Create the shape
    Set Shp = ActiveSheet.Shapes.AddShape( _
        Type:=msoShapeRectangle, _
        Left:=100, _
        Top:=10, _
        Width:=200, _
        Height:=100)

'   Hide the border
    Shp.Line.Visible = False

'   Add 2–color gradient
    With Shp.Fill
        .TwoColorGradient _
           Style:=msoGradientVertical, Variant:=2
        .ForeColor.RGB = RGB(255, 255, 255) 'white
        .BackColor.ObjectThemeColor = msoThemeColorAccent4
    End With
End Sub

The example on the CD–ROM includes additional code that creates the shapes shown in Figure 16-10: a shape with a pattern, a shape with a picture background (and a reflection), a shape with texture (and 3–D effects), and a shape that contains text.

These shapes were created with VBA macros.

Figure 16-10. These shapes were created with VBA macros.

Finding Out More about Shapes

The information in this section barely scratches the surface when it comes to working with Shape objects. Programming shapes with VBA could easily serve as the subject matter for a complete book.

To find out more about Shape objects, use the Object Browser (press F2 in the VBE), the Help system, the macro recorder (which is of limited value), and the Internet. And don't forget the best tool of them all: experimentation.

Modifying Chart Colors

This section describes how to change colors in a chart. The most important point is to identify the specific chart element that you want to modify. In other words, you need to identify the object and then set the appropriate properties.

Figure 16-11 shows a simple column chart named Chart 1. This chart has two data series, a legend, and a chart title.

A simple column chart.

Figure 16-11. A simple column chart.

Following is a VBA statement that changes the color of the first data series to red:

ActiveSheet.ChartObjects("Chart 1").Chart. _
    SeriesCollection(1).Format.Fill.ForeColor.RGB = vbRed

The object hierarchy is as follows:

The active sheet contains a ChartObjects collection. One object in that collection is the ChartObject named Chart 1. The Chart property of the ChartObject object returns a Chart object. The Chart object has a SeriesCollection collection, and the first Series object in the collection has an index number of 1. The Format property of the Series object returns a ChartFormat object. The Fill property of the ChartFormat object returns a FillFormat object. The ForeColor property of the FillFormat object returns a ColorFormat object. The RGB property of the ColorFormat object is set to red.

Following is another way of writing the preceding statement, using object variables to clarify and identify the object hierarchy:

Sub ChangeSeries1Color
    Dim MyChartObject As ChartObject
    Dim MyChart As Chart
    Dim MySeries As Series
    Dim MyChartFormat As ChartFormat
    Dim MyFillFormat As FillFormat
    Dim MyColorFormat As ColorFormat

'   Create the objects
    Set MyChartObject = ActiveSheet.ChartObjects("Chart 1")
    Set MyChart = MyChartObject.Chart
    Set MySeries = MyChart.SeriesCollection(1)
    Set MyChartFormat = MySeries.Format
    Set MyFillFormat = MyChartFormat.Fill
    Set MyColorFormat = MyFillFormat.ForeColor

'   Change the color
MyColorFormat.RGB = vbRed
End Sub

The RGB property accepts a decimal color value, which I specified using a built–in VBA constant. Alternatively, the color red can be expressed using this RGB function:

RGB(255, 0, 0)

If you prefer to set the color using a document theme color, two other color–related properties of the ColorFormat object are relevant:

  • ObjectThemeColor: A number between 0 and 16 that represents the theme color. VBA provides constants for these values. For example, msoThemeColorAccent3 contains the value 7.

  • TintAndShade: A number between −1 and +1 that represents the tint or shade of the theme color.

Note

The examples in this section are available on the companion CD–ROM. The filename is chart colors.xlsm.

You can also specify color gradients. Here's an example that applies a preset gradient to the second data series on a chart. Notice that the gradient is set using the FillFormat object:

Sub AddPresetGradient()
    Dim MyChart As Chart
    Set MyChart = ActiveSheet.ChartObjects("Chart 1").Chart
    With MyChart.SeriesCollection(1).Format.Fill
         .PresetGradient _
             Style:=msoGradientHorizontal, _
             Variant:=1, _
             PresetGradientType:=msoGradientFire
     End With
End Sub

Working with other chart elements is similar. The procedure that follows changes the colors of the chart's chart area and plot area, using colors from the current document theme:

Sub RecolorChartAndPlotArea()
    Dim MyChart As Chart
    Set MyChart = ActiveSheet.ChartObjects("Chart 1").Chart
    With MyChart
        .ChartArea.Format.Fill.ForeColor.ObjectThemeColor = _
             msoThemeColorAccent6
.ChartArea.Format.Fill.ForeColor.TintAndShade = 0.9
           .PlotArea.Format.Fill.ForeColor.ObjectThemeColor = _
                msoThemeColorAccent6
           .PlotArea.Format.Fill.ForeColor.TintAndShade = 0.5
    End With
End Sub

The final example in this section applies a random color to each chart element. Using this macro virtually guarantees an ugly chart. However, this code demonstrates how to change the color for other chart elements. The UseRandomColors procedure uses a simple function, RandomColor, to determine the color used.

Sub UseRandomColors()
    Dim MyChart As Chart
    Set MyChart = ActiveSheet.ChartObjects("Chart 1").Chart
    With MyChart
         .ChartArea.Format.Fill.ForeColor.RGB = RandomColor
         .PlotArea.Format.Fill.ForeColor.RGB = RandomColor
         .SeriesCollection(1).Format.Fill.ForeColor.RGB = RandomColor
         .SeriesCollection(2).Format.Fill.ForeColor.RGB = RandomColor
         .Legend.Font.Color = RandomColor
         .ChartTitle.Font.Color = RandomColor
         .Axes(xlValue).MajorGridlines.Border.Color = RandomColor
         .Axes(xlValue).TickLabels.Font.Color = RandomColor
         .Axes(xlValue).Border.Color = RandomColor
         .Axes(xlCategory).TickLabels.Font.Color = RandomColor
         .Axes(xlCategory).Border.Color = RandomColor
    End With
End Sub


Function RandomColor()
    RandomColor = Application.RandBetween(0, RGB(255, 255, 255))
End Function

The companion CD–ROM contains another example that applies random theme colors to the chart elements. If you run this procedure, you'll see that some chart objects cannot be colored with a theme color. Specifically, I was not able to find a way to change the color of the legend text or the axis labels. This appears to be a bug in the initial release of Excel 2007.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset