Count Cells by Background Color in Excel Using VBA Macro

📅 Sep 15, 2026 📝 Sarah Miller

Tracking project statuses using color-coded cells is highly intuitive, yet Excel frustratingly lacks a native formula to count cells by background color. While standard functions serve as the primary resource for data analysis-akin to relying on traditional funding sources to back your operations-they cannot read visual formatting. Fortunately, a custom VBA macro grants you the unique ability to bridge this functional gap. Keep in mind this stipulation: Excel does not trigger auto-recalculations based on formatting changes alone. However, implementing this tool allows you to seamlessly count green "Approved" rows. Below, we outline the exact VBA script and step-by-step formula setup.

Count Cells by Background Color in Excel Using VBA Macro

Excel Formula To Count Background Colors With VBA Macro

Excel is an incredibly powerful tool for data analysis, visual tracking, and project management. One of the most common ways users organize their spreadsheets is by using color coding. You might use green to indicate completed tasks, yellow for pending ones, and red for urgent issues. While this makes your data visually intuitive, analyzing it programmatically presents a challenge: Excel does not have a native formula to count or sum cells based on their background color.

While Excel offers powerful tools like conditional formatting and basic filtering by color, it lacks a standard worksheet function like =COUNTIFCOLOR(). Fortunately, we can easily bridge this gap by creating our own custom formula using Visual Basic for Applications (VBA). In this comprehensive guide, we will walk through how to write, implement, and use a VBA macro to count cells based on their background color.


Why Does Excel Lack a Native Color-Counting Formula?

Excel formulas are designed to analyze data values, not visual presentation. In spreadsheet design theory, formatting (such as fill color, font size, or borders) is considered "metadata"-information about the data, rather than the data itself. Because of this philosophy, Microsoft's standard formula engine ignores aesthetic properties.

To count or sum cells by color without VBA, you would have to rely on manual filters, which is time-consuming and prone to human error, or use advanced Power Query techniques. A custom VBA function (often called a User Defined Function, or UDF) is the most elegant, dynamic, and reusable solution available.


Step 1: Open the VBA Editor in Excel

To write our custom formula, we need to access the developer backend of Excel. Don't worry if you have never written code before; the process is straightforward.

  1. Open your Excel workbook where you want to count colors.
  2. Press Alt + F11 on your keyboard (or Option + F11 on a Mac). This action opens the Visual Basic for Applications (VBA) Editor.
  3. In the menu bar at the top of the VBA window, click on Insert and then select Module.
  4. A blank code window will appear on the right side of your screen. This is where we will paste our custom VBA macro.

Step 2: Paste the VBA Code for counting colors

Copy and paste the following VBA code into the blank module window you just created:

Function CountCellsByColor(SourceRange As Range, ColorSample As Range) As Long
    Dim Cell As Range
    Dim TargetColor As Long
    Dim MatchCount As Long
    
    ' Get the background color of the sample cell
    TargetColor = ColorSample.Interior.Color
    MatchCount = 0
    
    ' Loop through each cell in the selected range
    For Each Cell In SourceRange
        If Cell.Interior.Color = TargetColor Then
            MatchCount = MatchCount + 1
        End If
    Next Cell
    
    ' Return the total count
    CountCellsByColor = MatchCount
End Function

How This Code Works:

  • Function CountCellsByColor: This line defines a new custom function named CountCellsByColor that can be typed directly into your Excel cells just like SUM or AVERAGE.
  • SourceRange: This is the range of cells you want Excel to inspect (e.g., A1:A50).
  • ColorSample: This is a reference cell that contains the specific background color you want to count.
  • Cell.Interior.Color: The code looks at the background fill color property of each cell in your range and compares it to the target color. If they match, it increments our counter.

Step 3: How to Use Your New Formula in Excel

Now that the code is pasted into your module, you can close the VBA Editor and return to your Excel worksheet. Your custom formula is immediately ready for use.

The syntax for your new formula is:

=CountCellsByColor(Range_to_Count, Cell_with_Target_Color)

Practical Example:

Imagine you have a list of project tasks in cells A2:A20. Some cells are highlighted in light green (completed) and others in light red (delayed).

  1. In an empty cell (let's say C2), apply the exact light green background color you want to count.
  2. In the cell next to it (D2), enter the formula:
    =CountCellsByColor(A2:A20, C2)
  3. Press Enter. Excel will instantly return the total number of light green cells in your task list.
  4. You can repeat this process for the red cells by coloring cell C3 red and using the formula =CountCellsByColor(A2:A20, C3).

Crucial Limitation: The Recalculation Issue

There is an important quirk in Excel that you must understand when working with formatting-based formulas: Changing a cell's fill color does not trigger a recalculation in Excel.

Excel only recalculates formulas when data values change. If you change a cell's color from red to green, your formula output will not update automatically. To fix this, you have two options:

Option A: Force a Manual Recalculation

Whenever you change background colors and want your counts to update, press F9 (or Ctrl + Alt + F9) on your keyboard to force Excel to recalculate all formulas in the workbook.

Option B: Make the Function Volatile (Automated updates)

You can modify your VBA code to make the function "volatile." This means the formula will recalculate whenever any cell on the sheet is edited. To do this, add Application.Volatile to the start of your code:

Function CountCellsByColor(SourceRange As Range, ColorSample As Range) As Long
    Application.Volatile
    Dim Cell As Range
    Dim TargetColor As Long
    Dim MatchCount As Long
    
    TargetColor = ColorSample.Interior.Color
    MatchCount = 0
    
    For Each Cell In SourceRange
        If Cell.Interior.Color = TargetColor Then
            MatchCount = MatchCount + 1
        End If
    Next Cell
    
    CountCellsByColor = MatchCount
End Function

Note: While making a function volatile makes it more dynamic, it can slow down your workbook if you are working with extremely large datasets (tens of thousands of rows), as Excel will rerun the calculation constantly.


Bonus: Summing Values Based on Background Color

Often, users don't just want to count the colored cells; they want to sum the numbers inside those colored cells. You can easily do this by adding a second function to your VBA module. Paste this code directly below your first function:

Function SumCellsByColor(SourceRange As Range, ColorSample As Range) As Double
    Application.Volatile
    Dim Cell As Range
    Dim TargetColor As Long
    Dim TotalSum As Double
    
    TargetColor = ColorSample.Interior.Color
    TotalSum = 0
    
    For Each Cell In SourceRange
        If Cell.Interior.Color = TargetColor And IsNumeric(Cell.Value) Then
            TotalSum = TotalSum + Cell.Value
        End If
    Next Cell
    
    SumCellsByColor = TotalSum
End Function

Now, you can use =SumCellsByColor(A2:A20, C2) to add up all numerical values in the cells that match your target background color.


Important: Note on Conditional Formatting

It is vital to understand that the standard VBA Interior.Color property detects colors applied manually (using the fill bucket tool). If your cells are colored automatically using Conditional Formatting rules, this basic script will not count them.

In modern Excel (2010 and later), you can theoretically use Cell.DisplayFormat.Interior.Color to capture conditional formatting colors. However, Microsoft has blocked DisplayFormat from working inside User Defined Functions used directly in worksheet cells (it will return a #VALUE! error). If your colors are generated via Conditional Formatting, the best practice is to count the cells using the same mathematical logic as your conditional formatting rule using standard COUNTIFS formulas, rather than counting the visual colors themselves.


How to Save Your Workbook

Because your Excel workbook now contains VBA code, you cannot save it as a standard .xlsx file. If you do, Excel will strip away the macro, and your formula will stop working the next time you open the document.

  1. Click File > Save As.
  2. In the file type dropdown menu, select Excel Macro-Enabled Workbook (*.xlsm).
  3. Click Save.

Now, your custom color-counting formula is permanently embedded and ready to assist you in organizing your projects, budgets, and dashboards!

Disclaimer:
The documents and templates provided on this page are for informational and illustrative purposes only. They do not constitute professional, legal, or financial advice, and should not be relied upon as such. Because individual circumstances and regulatory requirements vary, these materials may not be suitable for your specific needs. We recommend consulting with a qualified professional before adapting or using any of these examples for official or commercial purposes.