How to Count or Sum Cells With Certain Color in Excel

Download Example Workbook

Download the example workbook

This tutorial will demonstrate you how to count or sum cells of a certain background color using VBA.

count sum cell color Main Function

Consider the following range in Excel.

count sum cell color 01

There is no built in Excel function to count colored cells. Instead we must create a User-Defined Function using VBA.

Count Cells – Create a VBA Custom Function

Counting how many cells are of a certain color using VBA is a matter of creating a user-defined function (UDF) that will loop through all the cells in the range, and determine if the background color of each cell matches the background color that you are testing for, and then using that function in the Excel worksheet.

In VBA, we create a function to count selected cells.

Function CountCellsByColor(rng As Range, ColorCell As Range) As Double
	Dim dblCount As Double
	Dim rngCell As Range
    'Loop throught each cell in the range
		For Each rngCell In rng
'check to see if the interior color is the same color as the cell you have selected
			If rngCell.Interior.Color = ColorCell.Interior.Color Then
				If IsNumeric(rngCell.Value) = True Then
'increase the count by 1 if the color is correct.
					dblCount = dblCount + 1
				End If
			End If
		Next
    'Return the value to Excel
	CountCellsByColor = dblCount
End Function

Then use this function in the worksheet to return the value.

=CountCellsByColor(B2:E10,G4)
  1. Click in the orange cell in G4, and click Insert Function.

STEP 01

  1. Select User Defined as the category, and then select CountCellsByColor as the function to use.

STEP 02

  1. Click OK.

STEP 03

  1. Highlight the range that contains all the colored cells.

STEP 04

  1. Select the ColorCell, and then Click OK.
    STEP 05

Repeat the process to Count the cells with a Green Background color.

=CountCellsByColor(B2:E10,G5)

Sum Cells – Create a Custom VBA Function

We create a similar custom function in VBA to sum the values of the cells of a certain color.

Function SumCellsByColor(rng As Range, ColorCell As Range) As Double
	Dim dblSum As Double
	Dim rngCell As Range
    'Loop throught each cell in the range
		For Each rngCell In rng
'check to see if the interior color is the same color as the cell you have selected
			If rngCell.Interior.Color = ColorCell.Interior.Color Then
				If IsNumeric(rngCell.Value) = True Then
'add the value to your variable if the color is correct
					dblSum= dblSum + rngCell.Value
				End If
			End If
		Next
    'Return the value to Excel
	SumCellsByColor = dblSum
End Function

We would then once again use this function in the Worksheet to sum up the required cells.

=SumCellsByColor(B2:E10,G7)

count sum cell color Final