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

时间:2016-07-07 13:10:49

标签: excel vba 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

1 个答案:

答案 0 :(得分:4)

使用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