Count the number of occurrences of each fill color over an arbitrary range of cell?

Viewed 24

My attempt is below, but it is totally off base, and I am new to VBA macros. I have only been able to write the most rudimentary type of functions.

Function lbrHrsTot(Rng As Range) As String Dim R As Long Dim G As Long Dim B As Long Dim Re As Long Dim Y As Long Dim S As Long

Dim Cell As Range
For Each Cell In Rng
    If Cell.Interior.Color = RGB(255, 0, 0) Then
        R = R + 1
    ElseIf Cell.Interior.Color = RGB(0, 176, 80) Then
        G = G + 1
    ElseIf Cell.Interior.Color = RGB(0, 176, 240) Then
        B = B + 1
    ElseIf Cell.Interior.Color = RGB(166, 166, 166) Then
        S = S + 1
    ElseIf Cell.Interior.Color = RGB(255, 192, 0) Then
        Y = Y + 1
    ElseIf Cell.Interior.Color = RGB(192, 0, 0) Then
        Re = Re + 1
    End If
Next Cell

lbrHrsTot = "Red " & R & " Green " & G & " Blue " & B & " Silver " & S & " Yellow " & Y & " Dark Red " & R

End Function

function result

1 Answers

Something like that could work. Loop through each Cell in the Rng and check its color.

Function lbrHrsTot(Rng As Range) As String
    Dim R As Long
    Dim G As Long
    Dim B As Long
    Dim Re As Long
    Dim Y As Long
    Dim S As Long

    Dim Cell As Range
    For Each Cell In Rng
        If Cell.Interior.Color = RGB(255, 0, 0) Then
            R = R + 1
        ElseIf Cell.Interior.Color = RGB(0, 176, 80) Then
            G = G + 1
        ElseIf Cell.Interior.Color = RGB(0, 176, 240) Then
            B = B + 1
        ElseIf Cell.Interior.Color = RGB(166, 166, 166) Then
            S = S + 1
        ElseIf Cell.Interior.Color = RGB(255, 192, 0) Then
            Y = Y + 1
        ElseIf Cell.Interior.Color = RGB(192, 0, 0) Then
            Re = Re + 1
        End If
    Next Cell

    lbrHrsTot = "Red " & R & " Green " & G & " Blue " & B & " Silver " & S & " Yellow " & Y & " Dark Red " & R
End Function

Consider using Select Case instead of the multiple If … ElseIf … End If.

Related