A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
I determined a way to do this regarding PowerPivot-based pivot tables. I have three possible pivot tables on 3 different sheets, and one function for them all (called by a button on each sheet).
.Range("B4") below is where the first column and row of the pivot table is, so you know which pivot field to collapse.
The secret is the last line of code. It isn't ShowDetail True/False, apparentlyfor PowerPivot it is DrilledDown True/False.
Dim pt As PivotTable, pf As PivotField
Select Case ActiveSheet.Name
Case "Sheetname1"
Set pt = .PivotTables("PivotTable1")
Set pf = pt.PivotFields("[PowerPivot table name].[" & .Range("B4") & "].[" & .Range("B4") & "]")
Case "Sheetname2"
Set pt = .PivotTables("PivotTable6")
Set pf = pt.PivotFields("[PowerPivot table name].[" & .Range("B4") & "].[" & .Range("B4") & "]")
Case "Sheetname3"
Set pt = .PivotTables("PivotTable2")
Set pf = pt.PivotFields("[PowerPivot table name].[" & .Range("B4") & "].[" & .Range("B4") & "]")
End Select
pf.DrilledDown = False
One way to get the full name of the pivot fields is with this snippet:
wbBook.Worksheets(SheetName).Activate
With Worksheets("SheetName").PivotTables(1)
For i = 1 To .PivotFields.Count
MsgBox .PivotFields(i).Name
Next
End With
One last comment: I only figured this out by recording a macro and then clicking the collapse field menu option for the pivot table. Then I looked at the resulting VBA code and 'there it was'!
Hope this helps.