首页 > 解决方案 > 条件格式,虽然应用了没有格式出现

问题描述

首先,这是我去过的最好的论坛之一。我最近才创建了一个帐户,但我已经从这个论坛学到了很多东西。

根据标题,我的问题是关于条件格式的。如下代码所示,到目前为止,我已经应用了背景颜色作为格式。但是在运行此宏后,虽然条件已应用于选定的单元格,但它并没有格式化。当我单击管理现有规则时,条件存在,但出现“无格式集”。可以在这里看到:截屏

Sub tableSetup()

    Dim tbl As ListObject

    Set tbl = ActiveSheet.ListObjects.Add(SourceType:=xlSrcRange, Source:=Selection, xllistobjecthasheaders:=xlYes, tablestylename:="Custom")

    cellStr = tbl.DataBodyRange.Cells(1).Address
    cellStr = Replace(cellStr, "$", "")
    formulaStr = "=IsFormula(" & cellStr & ")"

    With tbl.DataBodyRange
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:=formulaStr
        .FormatConditions.Interior.Color = RGB(191, 191, 191)
    End With

End Sub

标签: vbaexcelconditional-formatting

解决方案


您没有告诉它要应用格式的 FormatConditions。

With tbl.DataBodyRange
    .FormatConditions.Delete
    .FormatConditions.Add Type:=xlExpression, Formula1:=formulaStr
    .FormatConditions(.FormatConditions.Count).Interior.Color = RGB(191, 191, 191)
End With

您已经合法地删除了所有其他 .FormatConditions,这可以称为 .FormatConditions(1) 但是当您添加 .FormatConditions 时,它始终是队列中的最后一个,直到您执行类似 .FormatConditions(.FormatConditions. Count).SetFirstPriority 将其移动到队列的前面。

您还可以使用使用 .FormatConditions.Add 创建的对象来形成嵌套的 With ... End With 块,以正确引用多个操作。

With tbl.DataBodyRange
    .FormatConditions.Delete
    with .FormatConditions.Add(Type:=xlExpression, Formula1:=formulaStr)
        .Interior.Color = RGB(191, 191, 191)
        .SetFirstPriority
    end with
End With

推荐阅读