如何更新/更改所有条件规则范围的最后一行

时间:2015-10-20 09:26:00

标签: excel vba excel-vba excel-2013 conditional-formatting

以下是我们的条件格式规则:

enter image description here

虽然每个AppliesTo范围的第一行始终为5,但实际情况要复杂得多。

导入新数据后,每个AppliesTo范围的最后一行可能会更改为15。

如何使用vba来应用此更改?

这是我们当前的循环,找到每个AppliesTo范围:

Sub updateAllCondFormatRules()

    Dim x As Excel.FormatCondition
    Dim r As Range

    Dim lastRw  As Integer
    Dim newLastRw  As Integer
    newLastRw = 15

    For Each x In ActiveSheet.Cells.FormatConditions
        Set r = x.AppliesTo
        MsgBox r.Address

        '>>here we need to change r so that the new last row is equal to newLastRw

        x.ModifyAppliesToRange r
    Next x

End Sub

1 个答案:

答案 0 :(得分:3)

我遇到了x对象类型的问题,但此代码似乎有效:

Sub updateAllCondFormatRules()

    Dim x As Excel.FormatCondition
    Dim r As Range
    Dim lastRw  As Long
    Dim newLastRw  As Long

    newLastRw = 20

    For Each x In ActiveSheet.Cells.FormatConditions
        Set r = x.AppliesTo

        MsgBox r.Address
        '>>here we need to change r so that the new last row is equal to newLastRw
        'Set r = ActiveSheet.Range(Replace(r.Address, Split(r.Address, "$")(UBound(Split(r.Address, "$"))), newLastRw))
        Set r = r.Resize(newLastRw - r.Cells(1, 1).Row + 1, r.Columns.Count)
        MsgBox r.Address

        x.ModifyAppliesToRange r
    Next x

End Sub