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

Aid*_*son 5 excel vba pivot-table

我在 VBA 中创建了一个充满字符串数据的数据透视表,但似乎无法折叠数据透视表中的所有字段,我该怎么做?这是我的源代码

    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
Run Code Online (Sandbox Code Playgroud)

R3u*_*3uK 6

千万不要使用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
Run Code Online (Sandbox Code Playgroud)