» Sum by color using VBA in Microsoft Excel
VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions
CATEGORY - Custom Functions , Printing in VBA
VERSION - All Microsoft Excel Versions
With the custom function below you can add the contents of cells depending on their background color:
Function SumByColor(InputRange As Range, ColorRange As Range) As Double
' returns the sum of each cell in the range InputRange that has the same
' background color as the cell in ColorRange
' example: =SumByColor($A$1:$A$20,B1)
' range A1:A20 is the range you want to sum
' range B1 is a cell with the background color you want to sum
Dim cl As Range, TempSum As Double, ColorIndex As Integer
' Application.Volatile ' this is optional
ColorIndex = ColorRange.Cells(1, 1).Interior.ColorIndex
TempSum = 0
On Error Resume Next ' ignore cells without values
For Each cl In InputRange.Cells
If cl.Interior.ColorIndex = ColorIndex Then
TempSum = TempSum + cl.Value
End If
Next cl
On Error GoTo 0
Set cl = Nothing
SumByColor = TempSum
End Function
The function is used in the same way as the built-in worksheetfunctions.
InputRange contains the cells with the values that the function is going to add,
ColorRange is a cell reference to a cell containing the background color you want restrict the adding to.
In Excel 5/95 the variables InputRange and ColorRange must be declared as Variant instead of Range.
The function can easily be adapted for use with other worksheetfunctions that you want to use on cells
with different background colors.
Book Store:
Recommended Books:
- Special Edition Using Microsoft Access 2002
- Treason: Liberal Treachery from the Cold War to the War on Terrorism
- The Basics of Finance: Financial Tools for Non Financial Managers
- Successful Business Planning in 30 Days: A Step-By-Step Guide for Writing a Business Plan and Starting Your Own Business
- How to Use Financial Statements: A Guide to Understanding the Numbers
- The Total Money Makeover. : A Proven Plan for Financial Fitness
No comments have been submitted.

