I have a workbook with about 120 tabs, each containing one or two pivot tables. The pivot tables are updated and refreshed monthly. I am struggling to write a macro that will collapse all prior year data.
This code works, but I would need to update it and re-run it for each prior year:
Dim ws As Worksheet
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1"& "*" Or ws.Name Like "2"& "*" Or ws.Name Like "3"& "*" Then
ws.PivotTables("PivotTable1").PivotFields("Years").PivotItems("2015"). _
ShowDetail = False
On Error Resume Next
ws.PivotTables("PivotTable2").PivotFields("Years").PivotItems("2015"). _
ShowDetail = False
End If
Next ws
End Sub
I would prefer code that can collapse all prior year data.
I have tried the following, and it produces a run-time error 438 object doesn't support this property or method:
Dim ws As Worksheet
Dim datecell As Range
Dim cy As Long
Application.ScreenUpdating = False
Set datecell = ThisWorkbook.Worksheets("Index").Range("H1")
cy = Year(datecell)
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1"& "*" Or ws.Name Like "2"& "*" Or ws.Name Like "3"& "*" Then
'the following line produces the run-time 438 object doesn't support this property or method error
If Year(ws.PivotTables("PivotTable1").PivotFields("Years").PivotItems) < cy Then
PivotItem.ShowDetails = False
End If
End If
Next ws
End Sub
I have also tried the following, and it produces a run-time error 13 type mismatch:
Dim ws As Worksheet
Dim datecell As Range
Dim cy As Long
Application.ScreenUpdating = False
Set datecell = ThisWorkbook.Worksheets("Index").Range("H1")
cy = Year(datecell)
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1"& "*" Or ws.Name Like "2"& "*" Or ws.Name Like "3"& "*" Then
For Each PivotItem In ws.PivotTables("PivotTable1").PivotFields("Years").PivotItems
'the following line produces the run-time 13 type mismatch error
If Year(PivotItem) < cy Then
PivotItem.ShowDetails = False
End If
Next PivotItem
End If
Next ws
End Sub
Does anyone know how to correct my code? Thanks!
Edit 1: The following code produces a run-time error 438: Object doesn't support this property or method:
Dim ws As Worksheet
Dim pt As PivotTable
Dim ptItm As PivotItem
Dim datecell As Range
Dim cy As Long
Dim ptItmY As Long
Application.ScreenUpdating = False
Set datecell = ThisWorkbook.Worksheets("Index").Range("H1")
cy = Year(datecell)
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "1"& "*" Or ws.Name Like "2"& "*" Or ws.Name Like "3"& "*" Then
For Each pt In ws.PivotTables
For Each ptItm In pt.PivotFields("Years").PivotItems
ptItmY = Right(ptItm, 4)
If ptItmY < cy Then
'the following line produces run-time error 438: Object doesn't support this property or method
ptItm.ShowDetails = False
Else: ptItm.ShowDetails = True
End If
Next ptItm
Next pt
End If
Next ws
End Sub