Excel 应用条件格式的宏

Excel Macro to apply conditional formatting

这是我的第一个宏项目,我正在努力弄清楚如何修复它。 我想用黄色突出显示范围内的同一列,但在 运行 之后突出显示范围内的所有内容。对我有什么见解吗?

这就是我想看到的。

事情是这样的。

这是我复制的代码

https://www.bluepecantraining.com/portfolio/excel-vba-macro-to-apply-conditional-formatting-based-on-value/

然后修改了。

Sub test()

    Dim rg As Range
    Dim cond1 As FormatCondition, cond2 As FormatCondition
    Set rg = Range("$C:$AG")

    'clear any existing conditional formatting
    rg.FormatConditions.Delete

    'define the rule for each conditional format
    Set cond1 = rg.FormatConditions.Add(xlCellValue, xlEqual, "weekday(C)=7")
    Set cond2 = rg.FormatConditions.Add(xlCellValue, xlEqual, "weekday(C)=1")


    'define the format applied for each conditional format
    With cond1
        rg.Interior.Color = vbYellow
        rg.Font.Color = vbBlack
    End With

    With cond2
        rg.Interior.Color = vbYellow
        rg.Font.Color = vbBlack
    End With

End Sub
  1. Type 参数更改为 xlExpression
  2. 在您的 With 语句中,您应该删除 rg。您正在做的是将格式应用于范围 (rg) 本身,而不是 FormatCondition 对象 (cond1/cond2).
Sub test()

    Dim rg As Range
    Dim cond1 As FormatCondition, cond2 As FormatCondition
    Set rg = Range("$C:$AG")

    'clear any existing conditional formatting
    rg.FormatConditions.Delete

    'define the rule for each conditional format
    Set cond1 = rg.FormatConditions.Add(xlExpression, xlEqual, "=WEEKDAY(C)=7")
    Set cond2 = rg.FormatConditions.Add(xlExpression, xlEqual, "=WEEKDAY(C)=1")


    'define the format applied for each conditional format
    With cond1
        .Interior.Color = vbYellow
        .Font.Color = vbBlack
    End With

    With cond2
        .Interior.Color = vbYellow
        .Font.Color = vbBlack
    End With

End Sub