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

问题描述 投票:1回答:2

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

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

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:无法设置数据透视表类的小计属性

excel vba pivot-table subtotal
2个回答
0
投票

答案在Microsoft'sPivotField.Subtotals的解释中描述。

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

只能为非数据字段定义小计。所以你不能循环所有的PivotFields,而是RowFields(或ColumnFields)。通过这个你也可以省略On Error Resume Next

由于ColumnGrandRowGrand是每个pivottable定义的,我把它放在循环之前。

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

1
投票

你需要遍历每个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
© www.soinside.com 2019 - 2024. All rights reserved.