如果它有多个数据字段,我无法从数据透视表中删除所有小计。
无论它有多少行或列标签,只要它只有一个数据字段就可以工作。这是我的代码:
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
的解释中描述。
如果要关闭所有小计类型,可以将Automatic
小计设置为True
(关闭所有其他类型)和False
,或者使用给定的数组符号将所有12种类型设置为False
。
只能为非数据字段定义小计。所以你不能循环所有的PivotFields
,而是RowFields
(或ColumnFields
)。通过这个你也可以省略On Error Resume Next
。
由于ColumnGrand
和RowGrand
是每个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
你需要遍历每个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