I have two sheets: Sheet2 and Sheet3. The goal was to highlight the cells in column A of sheet3 that has a match in column A of sheet2. Here's sheet2: enter image description here . Here's for sheet3: enter image description here
Now I used this formula to determine if there's a match: =SUM(--(A2=Sheet2:$A$2:$A$4))>0
Now here's the vba code that I used to implement the conditional formatting:
Dim rng As Range
Set rng = ThisWorkbook.Worksheets("Sheet3").Range("A2:A6")
With rng
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:="=SUM(--(A2=Sheet2!$A$2:$A$4))>0"
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
End With
So here's the problem: The code only highlights the first cell as shown in the image of sheet3, but there are other cells that met the criteria. I've tried recording the conditional format and run the code but it also does the same. The formula works fine if you do manual conditional formatting. I hope someone can elucidate this problem for me. Thanks.
xlExpression
)I would rather use the following formula:
=ISNUMBER(MATCH(A2,Sheet2:$A$2,$A$4,0))
(Replace the commas with semicolons if necessary.)
I don't know why your formula is not working. As you said, it is applied only to the first cell.
Links
FormatConditions object
FormatCondition object
FormatCondition.SetFirstPriority method
FormatCondition.StopIfTrue property
The Code
Option Explicit
' "=ISNUMBER(MATCH(A2,Sheet2!$A$2:$A$4,0))"
' "=SUM(--(A2=Sheet2!$A$2:$A$4))>0"
Sub cformatExpression()
Dim rng As Range: Set rng = ThisWorkbook.Worksheets("Sheet3").Range("A2:A6")
With rng.FormatConditions
.Delete
.Add xlExpression, , "=ISNUMBER(MATCH(A2,Sheet2!$A$2:$A$4,0))"
' Refer to last added (our) condition
' ('short' for: 'rng.FormatConditions(rng.FormatConditions.Count)').
With .Parent.FormatConditions(.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
'.StopIfTrue = False ' Note, default is 'True' in VBA.
End With
End With
End Sub
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.