Just recently I was asked if it was possible to sum a range of cells by their cell colour, rather than counting the number of cells with a matching colour. Well it is. To sum a range of cells based upon their background colour requires a custom function to be written and the a small formula to be written on the worksheet.
I was asked was it possible to sum a range of cells based on two different cell colours. Red and Yellow. Red representing a negative figure and yellow a positive number. To start with you need to add a custom function to a new module in Excel’s Visual Basic editor. Once you have created a new module copy the below function and paste it in to the module.
Function SumIfByColour(InputRange As Range, ColorRange As Range) As Double
Dim clr As Range
Dim ColourSum As Long
Dim ColorIndex As Integer
PositiveColour = 6 'Yellow Background
NegativeColour = 3 'Red Background
ColourSum = 0
On Error Resume Next ' ignore cells without values
For Each clr In InputRange.Cells
If clr.Interior.ColorIndex = PositiveColour Or clr.Interior.ColorIndex = NegativeColour Then
ColourSum = ColourSum + clr.Value
End If
Next clr
On Error GoTo 0
Set clr = Nothing
SumIfByColour = ColourSum
End Function
Once you have done this go back to your worksheet. Now let’s assume you have a list of numbers, positive and negative in column A ranging from A1 to A20. At the bottom of your list, or in cell B1 type the following formula:
=SumIfByColour(A1:A20,A1:A20)
Once typed hit enter and you will have your total! :-)
You may be asking, what if I have different colour backgrounds, or only one colour?
To sum different colours than those in this example you simply need to get the ColorIndex (which is a number) for the colours you are using. Getting the colour index is fairly easy and there is a guide here. Or you could simply look up the ColorIndex value using this chart I have prepared earlier!
I only have one colour I hear you say…. Well just modify the code slightly as shown below.
NegativeColour = 3 'Red Background – REMOVE THIS LINE
CHANGE THIS LINE
If clr.Interior.ColorIndex = PositiveColour Or clr.Interior.ColorIndex = NegativeColour Then
TO
If clr.Interior.ColorIndex = PositiveColour Then
Hey presto!
I hope you found this post useful!?
Recent Comments