[英]Excel VBA Conditional Formatting Custom Formula
I have two sheets: Sheet2 and Sheet3.我有两张纸:Sheet2 和 Sheet3。 The goal was to highlight the cells in column A of sheet3 that has a match in column A of sheet2.
目标是突出显示 sheet3 的 A 列中与 sheet2 的 A 列匹配的单元格。 Here's sheet2: enter image description here .
这是 sheet2:在此处输入图像描述。 Here's for sheet3: enter image description here
这是 sheet3:在此处输入图像描述
Now I used this formula to determine if there's a match: =SUM(--(A2=Sheet2:$A$2:$A$4))>0
现在我使用这个公式来确定是否存在匹配:
=SUM(--(A2=Sheet2:$A$2:$A$4))>0
Now here's the vba code that I used to implement the conditional formatting:现在这是我用来实现条件格式的 vba 代码:
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.所以问题来了:代码只高亮了第一个单元格,如 sheet3 的图像所示,但还有其他符合条件的单元格。 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
)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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.