简体   繁体   中英

Excel VBA: Checking if range contains a cell with a specific color

I have the following two user defined functions:

Function GetFillColor(Rng As Range) As Long
    GetFillColor = Rng.Interior.ColorIndex
End Function

and

Function ContainsColor(Rng As Range, Clr As Long) As Boolean
    ContainsColor = False
    For Each c In Rng
        If GetFillColor(c) = Clr Then
            ContainsColor = True
            Exit For
        End If
    Next
End Function

The second function does not seem to work when called like ContainsColor(A1:A5,35), what am I missing? Thanks.

Not so sure why you have 2 Functions , you can just use one:

Function ContainsColor(Rng As Range, Clr As Long) As Boolean

    Dim c As Range
    ContainsColor = False
    For Each c In Rng
        If c.Interior.ColorIndex = Clr Then
            ContainsColor = True
            Exit For
        End If
    Next

End Function

Calling it from Excel (in this case will result True, as Cell A1 Interior.ColorIndex = 35) :

在此处输入图片说明

sorry to resurrect an old issue, but I have this exactl formula working in an Excel spreadsheet, and I see that if I change the color of the cell in order to change the output, the result does not automatically update. I have to F2 in the formula cell and press enter for it to update ? Is there a way to have this aut refresh as the color changes ?

"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM