如何使用 VBA 修改单元格条件格式规则的“应用于”属性?

如何使用 VBA 修改单元格条件格式规则的“应用于”属性?

我正在尝试使用 VBA 创建条件格式规则并将其应用于多个单元格。

我尝试过只为一个单元格创建规则,然后编辑每个 formatcondition 对象的 applyto 属性。请参见此处:

Sub test()

    Dim strRange As String
    Dim myRange As Range

    strRange = "$B$4,$B$9:$BS$9"

    With Sheets("Sheet1").Range("B4") 
        .FormatConditions.Delete
        .FormatConditions.Add xlExpression, xlEqual, "=ISBLANK(RC)"
        .FormatConditions(.FormatConditions.Count).SetFirstPriority
        .FormatConditions(1).StopIfTrue = True
        .FormatConditions(1).AppliesTo = strRange
    End With


    End Sub

这似乎不起作用,因为一旦到达 AppliesTo 行,它实际上会改变单元格本身的值,而不是修改格式条件的 AppliesTo 属性。

修改单元格条件格式规则的“应用于”属性的最佳方法是什么?

我知道我可以修改“with”语句以包含我想要修改的其他单元格;而不仅仅是单元格 B4。这样做的问题是 range() 对象只能接受不超过 1024 个字符的字符串参数。事实上,我想将此规则应用于大量不连续的单元格,以突破 1024 个字符的限制。

答案1

有一种ModifyAppliesToRange方法为此目的而设计。您还需要转换strRange为 Range 对象。

.FormatConditions(1).AppliesTo = strRange 用。。。来 代替 .FormatConditions(1).ModifyAppliesToRange Range(strRange)

答案2

我遇到了类似的问题,剪切和粘贴单元格后条件格式应用于多个区域。例如,(E4:G4、E6:G6 等)。

基本上,我必须确定范围的范围,然后使用 ModifyAppliesToRange 来更新它。

Sub FixCondFormatDupRules()
'
Dim ws As Worksheet
Dim MyList As ListObject
Dim lRows As Long
Dim rngData As Range
Dim rngRow1 As Range
Dim rngRow2 As Range
Dim rngRowLast As Range

Set ws = ActiveSheet
Set MyList = ws.ListObjects(1)  'Note this only captures the first table in the ActiveSheet.  Wouldn't work if >1 table.
Set rngData = MyList.DataBodyRange
lRows = rngData.Rows.Count
Set rngRow1 = rngData.Rows(1)
Set rngRow2 = rngData.Rows(2)
Set rngRowLast = rngData.Rows(lRows)

With ws.Range(rngRow2, rngRowLast)
    .FormatConditions.Delete
End With

' Expanding the Conditional Formatting AppliesTo range to the extent of the ranges and to include the entire table column.
For Each col In rngRow1.Columns
    For Each fc In Range(col.Address).FormatConditions
        Set FirstCell = col                              'Find upper-left cell (lowest row, lowest col)
        Set LastCell = Cells(rngRowLast.Row, col.Column) 'Find lower-right cell (highest row, highest col)
        For Each xCell In fc.AppliesTo.Cells
            If xCell.Column < FirstCell.Column Then Set FirstCell = Cells(FirstCell.Row, xCell.Column)
            If xCell.Column > LastCell.Column Then Set LastCell = Cells(LastCell.Row, xCell.Column)
            If xCell.Row < FirstCell.Row Then Set FirstCell = Cells(xCell.Row, FirstCell.Column)
            If xCell.Row > LastCell.Row Then Set LastCell = Cells(xCell.Row, LastCell.Column)
        Next xCell
        fc.ModifyAppliesToRange Range(FirstCell, LastCell)
    Next fc
Next col

rngRow1.Cells(1, 1).Select
Application.CutCopyMode = False
End Sub

相关内容