Excel VBA User Defined Function that counts cells with conditional formatting

You can work around the inability to access DisplayFormat in a UDF using Evaluate

Function DFColor(c As Range)
    DFColor = c.DisplayFormat.Interior.Color
End Function


Function CountCellsByColor1(rData As Range) As Long
    Dim cntRes As Long, clr As Long, cell As Range
    cntRes = 0
    For Each cell In rData.Cells
        'Evaluate the formula string in the context of the
        '  worksheet hosting rData
        clr = rData.Parent.Evaluate("DFColor(" & cell.Address() & ")")
        If clr <> 16777215 Then
            cntRes = cntRes + 1
        End If
    Next cell
    CountCellsByColor1 = cntRes
End Function

Leave a Comment