VBA - 条件格式化多个单元格范围和循环

VBA - Conditional Formatting Multiple Ranges of Cells and Looping

我正在为工作创建一个主计划,并试图显示信息,以便对用户来说非常直观。

所以...我们希望能够在单元格 K4 中输入日期时突出显示单元格 J4:L4。然后,我们要循环第 4 行到 2500 行和 M:0、P:R、S:U 等列......我编写了以下宏,但它只突出显示第一个排。有人能指出我正确的方向吗?

    Sub Highlight()
    '
    ' Highlight Macro
    '
    ' Keyboard Shortcut: Ctrl+Shift+R
    '
    Dim kRange As Range, k As Integer, aaaFormat As FormatCondition
        If ActiveSheet.Name <> Sheet1.Name Then Exit Sub
    For k = 4 To 2500
        Set kRange = Range("=$J4:$L4")
        If kRange.FormatConditions.Count <> 0 Then
            kRange.FormatConditions.Delete
        Else
            Set aaaFormat = kRange.FormatConditions.Add(xlExpression, xlFormula, "=$K4<>0")
            aaaFormat.Interior.Color = 15773696
        End If
    Next k
    End Sub

当您在循环中循环时,您需要调整 CF 规则将控制的范围以及确定其结果的公式。

'this,
Set kRange = Range("$J4:$L4")
'becomes,
Set kRange = Range("$J"& k & ":$L"& k)
'and this,
Set aaaFormat = kRange.FormatConditions.Add(xlExpression, xlFormula, "=$K4<>0")
'becomes,
Set aaaFormat = kRange.FormatConditions.Add(xlExpression, xlFormula, "=$K" & k & "<>0")

但是,由于您已经将行设为相对,将列设为绝对,您只需将 CF 写入整个范围即可。

Sub Highlight()
    ' Highlight Macro
    ' Keyboard Shortcut: Ctrl+Shift+R

    With Sheet1.Range("J4:L2500")
        .FormatConditions.Delete
        With .FormatConditions.Add(Type:=xlExpression, Formula1:="=$K4<>0")
            .Interior.Color = 15773696
        End With
    End With
End Sub