如果数据透视表具有多个数据字段,我无法从该数据透视表中删除所有小计。
无论它有多少行或列标签,只要它只有一个数据字段,它就可以工作。这是我的代码:
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: 无法设置数据透视字段类的小计属性
最佳答案
答案在 Microsoft's 中描述。 PivotField.Subtotals
的解释。
如果您想关闭所有小计类型,您可以将自动
小计设置为True
(关闭所有其他类型)并再次设置为 False
,或者使用给定的数组表示法将所有 12 种类型设置为 False
。
只能为非数据字段定义小计。因此,您不能循环遍历所有PivotFields
,而是循环遍历RowFields
(或ColumnFields
)。通过此,您还可以省略On Error Resume Next
。
由于 ColumnGrand
和 RowGrand
每个数据透视表定义一次,因此我将其放置在循环之前。
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
关于excel - 如何使用vba从具有多个数据字段的Excel数据透视表中删除小计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55753103/