vba vba中条件格式公式中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16445910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String in a conditional formatting formula in vba
提问by Antoni Gual Via
I want to format column G if column D has "AI" in the same row using VBA in Excel 2007.
如果 D 列在 Excel 2007 中使用 VBA 在同一行中有“AI”,我想格式化 G 列。
If i do it manually in the conditional formatting editor the formula =(D1 = "AI")
works correctly.
如果我在条件格式编辑器中手动执行,则公式=(D1 = "AI")
可以正常工作。
If i try to add this formula to the Formula1 clause of a FormatConditions.Add method i must put
="(D1 = ""AI"")"
or the interpreter complains. But this is copied literally with the doubled double quotes as the condition and the formatting does nothing.
如果我尝试将此公式添加到 FormatConditions.Add 方法的 Formula1 子句中,我必须放置
="(D1 = ""AI"")"
否则解释器会抱怨。但是这是用双双引号作为条件从字面上复制的,并且格式没有任何作用。
What should I put in Formula1 ?
我应该在公式 1 中放什么?
Antonio
安东尼奥
回答by sous2817
This worked for me:
这对我有用:
Sub Macro2()
Sheet1.Range("G1").Select
With Sheet1.Range("G:G")
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:="=F1=""AI"""
.FormatConditions(1).Interior.ColorIndex = 3
End With
End Sub
Also, using VBA to set conditional formatting has always been a bit wonky (for me at least). The only way I could get it to work was to select G1 and then set the formatting. I know typically you don't need to select, but in this case it's the only way I could get it to work.
此外,使用 VBA 设置条件格式一直有点不稳定(至少对我而言)。我可以让它工作的唯一方法是选择 G1,然后设置格式。我知道通常你不需要选择,但在这种情况下,这是我让它工作的唯一方法。
回答by user2140261
Use this formula:
使用这个公式:
=$F$1="AI"
=$F$1="人工智能"
This will result in the below.
这将导致以下结果。
In VBA you could do this:
在 VBA 中,你可以这样做:
="=$F=" + Chr (34) + "AI" + Chr (34) + ")"
Chr (34) is "
(double quote)
Chr (34) 是"
(双引号)
Also you could use:
你也可以使用:
If Range("F1") = "AI" Then Range("G1").Interior.Color = 65535
If Range("F1") = "AI" Then Range("G1").Interior.Color = 65535
回答by Declan_K
If you are doing this in VBA, then why are you using conditional formatting at all? Simply look at the value in G and set the format of F directly in the VBA code.
如果您在 VBA 中执行此操作,那么您为什么要使用条件格式?直接看G中的值,直接在VBA代码中设置F的格式即可。