我有这段代码:
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($B5=""ARC"",1,0)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = ColorSheet.Range("ARC_Color").Interior.Color
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($B5=""ALL"",1,0)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = ColorSheet.Range("ALL_Color").Interior.Color
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
有比此更多的块,基本上所有更改都是条件格式条件中引用的命名范围。
=IF($B5=""ALL"",1,0)
ColorSheet.Range("ALL_Color").Interior.Color
循环这个的最佳方法是什么? 所以我没有十个代码块完全相同?
我可以更改它以在单独的工作表上读取列表中的命名范围吗?
由于
答案 0 :(得分:2)
创建一个这样的过程,它在一个单独的工作表上循环一个范围,在这个例子中称为“变量”。范围只包含10个不断变化的值:
编辑:根据@ KillerSnail在注释中的修正进行了修改,并添加了一个参数来传递ColorSheet。
Sub LoopCF()
Dim wsVariables As Excel.Worksheet
Dim ColorSheet As Excel.Worksheet
Dim cell As Excel.Range
Set wsVariables = ThisWorkbook.Worksheets("Variables")
Set ColorSheet = ActiveSheet ' Change to suit your needs
'this range contains "All", "ARC", etc.
For Each cell In wsVariables.Range("A2:A11")
ApplyCF cell.Value2
Next cell
End Sub
然后你基本上从循环中调用你现有的代码,传递“ARC”,“ALL”和其他变量。
Sub ApplyCF(wsColorSheet As Excel.Worksheet, ConditionToCheck As String)
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($B5=" & Chr(34) & ConditionToCheck & Chr(34) & ",1,0)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = wsColorSheet.Range(ConditionToCheck & "_Color").Interior.Color
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub