简体   繁体   中英

VBA How do I conditionally format a range of cells based on the value of one cell in that range?

My goal is to have the text of the entire row turn grey if the value of a particular cell in that row shows "GAT1". I can do this fine with regular conditional formatting but am struggling to figure out how to automate the creation of this formatting with a macro.

My problem really comes down to the fact that the criteria for my formatting uses a formula to specify the text string. My understanding is that I usually have to put text strings in quotes or VBA will not recognize them as such, however the syntax of VBA will not allow me to put the said text string in quotes as the formula containing this string is already enclosed in quotes itself. (eg I was trying to write my condition as such - Formula1:="=F1="GAT1"" or Formula1:="=F1=GAT1" but neither of these options produces the desired result)

The code below is my most recent attempt. I've tried separating out the text string and concatenating it together but this hasn't worked.

Dim MyRange As Range

Set MyRange = Range("A1:P200")
    MyRange.FormatConditions.Add Type:=xlExpression, Formula1:="=$F1" & "=GAT1"
        With MyRange.FormatConditions(1)
            .Font.Color = RGB(217, 217, 217)
        End With

Any ideas on how to resolve this issue are much appreciated.

Like this:

Dim MyRange As Range

Set MyRange = Range("A1:P200")
With MyRange.FormatConditions.Add(Type:=xlExpression, Formula1:="=$F1=""GAT1""")
    .Font.Color = RGB(217, 217, 217)
End With

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