Identifying Number of Cells with Certain Colour in Excel

Abstract: Resolve the inability to count colored cells in Excel by creating a custom VBA function that accurately tallies cells based on their background fill color.

Created: 2026-07-29 by
You cannot count colored cells with standard Excel formulas because the CELL function does not return interior color information. To solve this, you must use a User Defined Function (VBA macro) or a helper column with manual tagging. This article explains how to create a custom VBA function that accurately counts cells based on their background fill color.

Why Standard Formulas Fail for Color Counts

Many users attempt to use functions like COUNTIF, SUMIF, or COUNTIFS to count cells by color. These functions operate exclusively on cell values, such as numbers, text, or dates. They have no capability to inspect the formatting properties of a cell, such as its font color, border style, or interior fill.

While the CELL function can return information about a cell's address, file name, and width, it explicitly excludes color data. Consequently, any formula-based approach that claims to count colors without VBA is either relying on a hack involving conditional formatting rules (which are dynamic and hard to parse) or is simply incorrect. Understanding this limitation is crucial before attempting to build a solution.

Creating a Custom VBA Function

The most reliable method to count colored cells is to create a User Defined Function (UDF) using Visual Basic for Applications (VBA). This custom function will iterate through a specified range and check the interior color property of each cell.

Accessing the VBA Editor

To begin, press Alt + F11 on your keyboard to open the Microsoft Visual Basic for Applications editor. In the Project Explorer window on the left, right-click on your workbook name or the VBAProject object. Select Insert and then choose Module. This creates a new blank code module where you will write your function.

Writing the Code

Copy and paste the following code into the module window. This function takes two arguments: the range of cells you want to check, and the reference cell whose color you want to match.

Function CountColoredCells(pRange As Range, pColorRef As Range) As Long
    Dim rngCell As Range
    Dim lColorIndex As Long
    Dim lCount As Long
    
    ' Get the color index of the reference cell
    lColorIndex = pColorRef.Interior.ColorIndex
    
    ' Loop through each cell in the provided range
    For Each rngCell In pRange
        If rngCell.Interior.ColorIndex = lColorIndex Then
            lCount = lCount + 1
        End If
    Next rngCell
    
    ' Return the total count
    CountColoredCells = lCount
End Function

This code defines a function named CountColoredCells. It first captures the Interior.ColorIndex of the reference cell (pColorRef). It then loops through every cell in the target range (pRange), comparing each cell's color index to the reference. If they match, it increments the counter. Finally, it returns the total count as a long integer.

Using the Function in Your Worksheet

Once the code is saved, close the VBA editor and return to your Excel worksheet. The function behaves like any other built-in Excel function.

  1. Select the cell where you want the result to appear.
  2. Type =CountColoredCells(.
  3. Select the range of cells you wish to analyze (e.g., A1:A100).
  4. Type a comma to separate the arguments.
  5. Select a single cell that has the specific color you want to count (e.g., B1).
  6. Close the parenthesis and press Enter.

For example, if you want to count how many cells in A1:A50 are yellow, and cell B1 is filled with yellow, you would enter: =CountColoredCells(A1:A50, B1). This will return the exact number of cells matching that specific fill color.

Handling Conditional Formatting

A critical limitation of the VBA method above is that it checks the actual interior color value. If your cells are colored via Conditional Formatting, the Interior.ColorIndex may not reflect the visual color until the condition is evaluated, or it may return -4142 (xlColorIndexNone) if the base cell has no explicit fill.

If you need to count cells colored by Conditional Formatting, you must ensure the conditions are met so the colors render, or use a more complex VBA script that evaluates the DisplayFormat property instead of the Interior property. Using rngCell.DisplayFormat.Interior.ColorIndex inside the loop allows the function to see the color as it appears on screen, regardless of whether it comes from static fill or conditional rules.

Performance Considerations

Custom VBA functions recalculate only when their dependencies change, but they can be slow on very large ranges. If you are counting colors across tens of thousands of rows, consider limiting the range or using a helper column strategy. Alternatively, you can use the Application.Volatile statement at the top of the function to force it to recalculate every time the sheet changes, though this impacts performance. For most standard reports, the basic version provided above is sufficient and fast.

Related Resources

If you are working with complex data sets, you might also find it useful to group similar values together to simplify your analysis. See our guide on Excel Formula to group similar values for techniques on organizing data before applying color-based counts.

Additionally, if your colored cells contain text that needs cleaning, check out Removing Numbers from Text in Excel: A Step-by-Step Guide to ensure your underlying data is accurate before summarizing it.

Frequently Asked Questions

Can I count cells by font color instead of fill color?

Yes, you can modify the VBA code to check font color. Simply change rngCell.Interior.ColorIndex to rngCell.Font.ColorIndex in both the reference capture and the comparison loop. This allows you to count cells based on the color of the text rather than the background.

Why does my VBA function return zero even though cells look colored?

This usually happens because the cells are colored via Conditional Formatting, and the base cell has no explicit fill. The standard Interior.ColorIndex reads the base format, not the applied conditional format. You must switch to using DisplayFormat.Interior.ColorIndex in your VBA code to capture the visual color correctly.

Does this function work in Excel Online?

No, custom VBA macros do not run in Excel for the Web. You must use the desktop version of Excel (Windows or Mac) to create and execute UDFs. Excel Online supports limited scripting via Office Scripts, but not traditional VBA.

How do I count multiple different colors at once?

You can add multiple columns to your spreadsheet, each using the same CountColoredCells function but pointing to a different reference cell with a unique color. For example, one column counts red references, another counts blue, and so on. This provides a summary breakdown of all colored categories.

Is there a non-VBA way to count colors?

There is no native formula to count colors directly. However, you can manually tag cells by entering a marker (like "Y" or "N") in an adjacent helper column based on their color, and then use COUNTIF on that helper column. This is labor-intensive but requires no code.

Tags: Excel Formula

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More