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

これをループする最良の方法は何ですか? まったく同じコードのブロックが 10 個もないようにするには?

別のシートのリストから名前付き範囲を読み取るように変更できますか?

ありがとう

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 に答える