Check cell color in VBA

Each color in Excel has its index. You can get both background and font color with a shortcode. Let’s use the following example to illustrate how the code works.

Check cell background color

In order to check the cell background color, you have to use VBA. Press Alt + F11 to open VBA Editor. Insert a new module to the project.

We will use this function to determine the background color.

Function CheckBackgroundColor(cell As Range)
    If (cell.Cells.Count > 1) Then
        CheckBackgroundColor = "Enter one cell"
        Exit Function
    Else
        CheckBackgroundColor = cell.Interior.Color
    End If
End Function

code explanation

The following function checks whether the range parameter is only a single cell. If it’s not it, it will display a text informing you to enter a single cell as a parameter.

If you entered a single cell, the function displays its background color.

Check cell font color

You can quickly modify this function to works also with font color.

Function CheckFontColor(cell As Range)
    If (cell.Cells.Count > 1) Then
        CheckFontColor = "Enter one cell"
        Exit Function
    Else
        CheckFontColor = cell.Font.Color
    End If
End Function

This will give us the following result.

What you get is a color in decimal form. You may want to convert them into hexadecimal form.

=DEC2HEX(C2)

If you use it for the white text you will get FFFFFF.

Posted in vba