简体   繁体   中英

VBA applying conditional formatting to cell

I'm trying to add conditional formatting to a range that checks cell X1 and if it doesn't match it applies the conditions.

If i apply it to one cell it works great. however i need it applied to each cell in a range.

code:

    Function FindComment(rng As Range, strSearch As String) As Boolean

On Error GoTo err_h:

strSearch = LCase(strSearch)

If Len(strSearch) = 0 Then
    FindComment = False
    Exit Function
End If

If InStr(1, rng.Comment.Text, strSearch, vbTextCompare) > 0 Or InStr(1, rng.Text, strSearch, vbTextCompare) > 0 Then
    FindComment = False
    Exit Function
End If

FindComment = True
Exit Function

err_h:
    FindComment = True
End Function

And to apply the conditional formatting:

Public Sub AddConditionalFormat(rng As Range)

   rng.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=FINDCOMMENT(" & rng.Address(, , xlA1) & ",$X$1)"
    rng.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

    With Selection.FormatConditions(1).Font
        .ColorIndex = 2
    End With

    With rng.FormatConditions(1).Interior
        .Pattern = xlGray75
        .PatternThemeColor = xlThemeColorDark2
        .PatternTintAndShade = 0
        .ColorIndex = 2
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With

    rng.FormatConditions(1).StopIfTrue = False

End Sub

the range range("B6:GD9") are determined as rng.

currently if the results match it just blanks out all cells including the match.

anyone have an idea of how to easily fix? i'd prefer something that would not lag out the code by applying to each cell etc.

The Range.Address property defaults to absolute row and column references. You are looking for something like A1 but you are getting $A$1 .

rng.FormatConditions.Add Type:=xlExpression, Formula1:= _
    "=FINDCOMMENT(" & rng.Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyle:=xlA1) & ", $X$1)"
'alternate in shorthand
rng.FormatConditions.Add Type:=xlExpression, Formula1:= _
    "=FINDCOMMENT(" & rng.Cells(1, 1).Address(0, 0, xlA1) & ", $X$1)"

Using .Cells(1, 1) should make that formula reference the upper left cell in rng .

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