1

我有这个代码:

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

循环这个的最好方法是什么?所以我没有十个完全相同的代码块?

我可以更改它以从单独的工作表上的列表中读取命名范围吗?

谢谢

4

1 回答 1

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
于 2013-02-19T04:45:10.213 回答