首页 > 解决方案 > 不要格式化总计行/列

问题描述

我想出了下面的 VBA,它旨在将条件格式添加到数据透视表中,即使行和列项发生更改。我试图使用 rannge.resize 函数从这种条件格式中排除的列和行的总行数。

谁能解释为什么它不起作用?它仍然包括条件格式中的总计行和列。

Sub CondFormat()
Dim rg As Range
Dim cs As ColorScale
Set Rng = ActiveSheet.PivotTables(1).DataBodyRange
Rng.Resize(Rng.Rows.Count - 1, Rng.Columns.Count - 1).Select
Rng.FormatConditions.Delete
'colour scale will have three colours
Set cs = Rng.FormatConditions.AddColorScale(ColorScaleType:=3)
With cs
    'the first colour is green
    With .ColorScaleCriteria(1)
        .FormatColor.Color = RGB(70, 255, 90)
        .Type = xlConditionValuePercentile
        .Value = 10
    End With
    'the second colour is white set at value 18
    With .ColorScaleCriteria(2)
        .FormatColor.Color = RGB(255, 255, 255)
        .Type = xlConditionValuePercentile
        .Value = 80
    End With
    'the third colour is red
    With .ColorScaleCriteria(3)
        .FormatColor.Color = RGB(200, 130, 120)
        .Type = xlConditionValuePercentile
        .Value = 10
    End With
End With
End Sub

标签: excelvba

解决方案


尝试更换:

Set cs = Rng.FormatConditions.AddColorScale(ColorScaleType:=3)

Set cs = Rng.Resize(Rng.Rows.Count - 1, Rng.Columns.Count - 1).FormatConditions.AddColorScale(ColorScaleType:=3).

您这样做Set Rng = ActiveSheet.PivotTables(1).DataBodyRange总是Rng 绑定到完整的 databodyrange,即使您调整它的大小(您不会将调整大小保存到新的范围对象中)


推荐阅读