VBA 中的条件格式,相同的颜色,多个字符串?
Conditional formating in VBA, same color, multiple strings?
我有这个用于条件格式化的代码,其中我只更改字符串:
Cells.FormatConditions.Delete
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="CPA", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="CPN", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="CSS", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="RL", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
所有这些行是否有任何替代方法,以便我可以用更短、更有效的方式编写它?
此宏甚至为包含 "CPAzergfzergfer" 的单元格着色。我如何编写一个宏,其中我只为包含确切字符串的单元格着色?
您可以使用数组指定条件格式的条件,如下所示:
myArray = Array("CPA", "CPN", "CSS", "RL")
For myLoop = LBound(myArray) to UBound(myArray)
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:=myArray(myLoop), TextOperator:=xlEqual)
.Interior.Color = RGB(105, 191, 44)
End With
Next
我还更改了 TextOperator
,因此它应该只有 select 个与文本值匹配的项目,而不是 包含 [=17] 的 select 个项目=] 文本值。
Dave 的回答很棒。这是另一种选择。这将所有条件放在一个公式中,我认为这使得在不太好的条件格式对话框中管理起来更容易。
我打开了宏记录器并打开了 CF 对话框并输入了这个公式:
=OR(A1="CPA",A1="CPN",A1="CSS",A1="RL")
这是生成的代码的清理版本:
Sub Macro1()
ActiveSheet.Range("A1:H17").FormatConditions.Add Type:=xlExpression, Formula1:= _
"=OR(A1=""CPA"",A1=""CPN"",A1=""CSS"",A1=""RL"")"
Selection.FormatConditions(1).Interior.Color = RGB(105, 191, 44)
End Sub
我有这个用于条件格式化的代码,其中我只更改字符串:
Cells.FormatConditions.Delete
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="CPA", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="CPN", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="CSS", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:="RL", TextOperator:=xlContains)
.Interior.Color = RGB(105, 191, 44)
End With
所有这些行是否有任何替代方法,以便我可以用更短、更有效的方式编写它?
此宏甚至为包含 "CPAzergfzergfer" 的单元格着色。我如何编写一个宏,其中我只为包含确切字符串的单元格着色?
您可以使用数组指定条件格式的条件,如下所示:
myArray = Array("CPA", "CPN", "CSS", "RL")
For myLoop = LBound(myArray) to UBound(myArray)
With Range("$A:$H").FormatConditions.Add(Type:=xlTextString, String:=myArray(myLoop), TextOperator:=xlEqual)
.Interior.Color = RGB(105, 191, 44)
End With
Next
我还更改了 TextOperator
,因此它应该只有 select 个与文本值匹配的项目,而不是 包含 [=17] 的 select 个项目=] 文本值。
Dave 的回答很棒。这是另一种选择。这将所有条件放在一个公式中,我认为这使得在不太好的条件格式对话框中管理起来更容易。
我打开了宏记录器并打开了 CF 对话框并输入了这个公式:
=OR(A1="CPA",A1="CPN",A1="CSS",A1="RL")
这是生成的代码的清理版本:
Sub Macro1()
ActiveSheet.Range("A1:H17").FormatConditions.Add Type:=xlExpression, Formula1:= _
"=OR(A1=""CPA"",A1=""CPN"",A1=""CSS"",A1=""RL"")"
Selection.FormatConditions(1).Interior.Color = RGB(105, 191, 44)
End Sub