Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.
With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company.
Learn more about Allen...
Besides using values and text in your worksheets, Excel allows you to use colors to either enliven or provide meaning to your data. If you use colors in your worksheets, you may wonder if there is a way to count the number of cells that are formatted with a particular fill color. There is no intrinsic function in Excel to perform such a task, but you can certainly make one with a user-defined function. The following is an example of one that will count the number of cells in a range that are formatted with a yellow fill color:
Function CountYellow(MyRange As Range) Dim iCount As Integer Application.Volatile iCount = 0 For Each cell In MyRange If cell.Interior.ColorIndex = 6 Then iCount = iCount + 1 End If Next cell CountYellow = iCount End Function
To use the function, all you need to do is use a formula such as the following in a cell of your worksheet:
This example returns the number of cells in the range of A1:A99 that use the yellow fill color.
Notice in the CountYellow function that the cells are examined to see if the ColorIndex property is equal to 6. In other VBA coding you may be used to seeing near-English constants that define colors. In this case, the normal color constants don't work. Instead, the ColorIndex property works based on a set of index values into a particular palette of colors. If you are interested in seeing the various index values used for the different colors, take a look at the VBA online help file for the ColorIndex property.
Once you know how to walk through the cells in a range in this manner, it is easy to perform other types of operations based on the color used to fill cells in the range. For instance, instead of simply counting the number of cells, you could add up the values of the cells in the range, or you could find the average of the values in the range. All you need to do is to make the appropriate changes in the code in the innermost If ... End If structure.
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (1978) applies to Microsoft Excel 97, 2000, 2002, and 2003.
Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!