如何使用 vba 从具有多个数据字段的 excel pivot-table 中删除小计

How to remove subtotal from a excel pivot-table with mutiple data fields useing vba

如果数据透视表有多个数据字段,我无法从数据透视表 table 中删除所有小计。

不管它有多少行或列标签,只要它只有一个数据字段,它就可以工作。这是我的代码:

Option Explicit
Private Sub pivot_table()

    Dim wkb         As Workbook
    Dim sht         As Worksheet
    Dim sht2        As Worksheet
    Dim pvtcch      As PivotCache
    Dim pvttbl      As PivotTable
    Dim pvtrange    As Range
    Dim pvtfield    As PivotField
    '-------------------------------------------------------------------------
    Set wrb = ThisWorkbook
    Set sht = wkb.Sheets(Plan1)

    Set sht2 = wkb.Sheets.Add(After:=sht)
    sht2.Name = "PVTBL"
    With sht
        Set pvtrange = .Range("A1").CurrentRegion
            .ListObjects.Add(xlSrcRange, pvtrange, , xlYes).Name = "sourcepvt"
    End With

    Set pvtcch = wrb.PivotCaches.Create(SourceType:=xlDatabase, _
 SourceData:="sourcepvt")

    Set pvttbl = sht2.PivotTables.Add(PivotCache:=pvtcch, _
 TableDestination:=sht2.Range("A3"), TableName:="Report")

    With pivottbl
        'code to set the row and columns labels and datafields
        .RowAxisLayout xlTabularRow
        .RepeatAllLabels xlRepeatLabels
        On Error Resume Next
        For Each campos In .PivotFields
            campos.Subtotals(1) = False
            .ColumnGrand = False
            .RowGrand = False
        Next campos
    End With
    Set wrb = Nothing
    Set sht = Nothing
    Set sht2 = Nothing
End Sub

当我尝试使用代码时,我收到错误对话框运行时错误 1004: 无法设置数据透视字段 Class

的小计 属性

您需要遍历每个 PivotField 并更新每个 .Subtotals 属性。其中有 12 个。由于您不需要任何小计,因此将它们全部设置为 False。您需要忽略错误,这样循环才不会停止。

For Each pvtfield In pivottbl.PivotFields
    'Disable subtotals for all fields
    On Error Resume Next
    pvtfield.Subtotals = Array(False, False, False, False, False, False, _
        False, False, False, False, False, False)
    On Error GoTo 0
Next pvtfield

答案在 PivotField.SubtotalsMicrosoft's 解释中描述。

如果您想关闭 所有 小计类型,您可以将 Automatic 小计设置为 True(关闭所有其他类型)和再次为 False,或者使用给定的数组符号将所有 12 种类型设置为 False

只能为非数据字段定义小计。因此,您不能遍历所有 PivotFields,而是遍历 RowFields(或 ColumnFields)。这样你也可以省略 On Error Resume Next

由于 ColumnGrandRowGrand 每个数据透视表定义一次,我将其放在循环之前。

With pvttbl
    .RowAxisLayout xlTabularRow
    .RepeatAllLabels xlRepeatLabels
    ' defined once per pivottable:
    .ColumnGrand = False
    .RowGrand = False
    ' use RowFields only:
    For Each campos In .RowFields
        ' either this:
        campos.Subtotals(1) = True   ' Automatic on (= all other off)
        campos.Subtotals(1) = False  ' Automatic also off

        ' or that (all 12 off):
        'campos.Subtotals = Array(False, False, False, False, False, False, False, False, False, False, False, False)
    Next campos
End With