VBA数据透视表折叠所有字段

我已经在VBA中创build了一个包含string数据的数据透视表,但似乎无法折叠数据透视表中的所有字段,我该怎么做? 这是我的源代码

SrcData = ActiveSheet.Name & "!" & Range(Cells(1, 1), Cells(46, 3)).Address(ReferenceStyle:=xlR1C1) StartPvt = Sheets("Key Controls").Cells(2, 5).Address(ReferenceStyle:=xlR1C1) Set pvtCache = ActiveWorkbook.PivotCaches.Create( _ SourceType:=xlDatabase, _ SourceData:=SrcData) Set pvt = pvtCache.CreatePivotTable( _ TableDestination:=StartPvt, _ TableName:="PivotTable1") pvt.PivotFields("SOP Reference").Orientation = xlRowField pvt.PivotFields("Key Control ID").Orientation = xlRowField pvt.PivotFields("Key Control Name").Orientation = xlRowField 

不要使用pf.ShowDetail = False

这是一个效率的噩梦,你会卡住一个长时间,可能会崩溃的Excel!


使用的好方法是DrillTo

 Public Sub PivotTable_Collapse() Dim pT As PivotTable Dim pF As PivotField Set pT = ActiveSheet.PivotTables(1) With pT For Each pF In pT.RowFields pF.DrillTo pF.Name Next pF End With End Sub