Sub MakeCurrentMontyAndYearVisibleInPivotTable()
'
Dim iX As Integer
Dim bFound As Boolean
Range("A4").Select 'Select Date Header in Pivot Table
Selection.Group Start:=True, End:=True, Periods:=Array(False, False, False, _
False, True, False, True) 'Group by Months & Years
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Years")
bFound = False
For iX = 1 To ActiveSheet.PivotTables("PivotTable1").PivotFields("Years").PivotItems.Count
If ActiveSheet.PivotTables("PivotTable1").PivotFields("Years").PivotItems(iX).Name = CStr(Year(Now())) Then
bFound = True 'Current Year data is present
Exit For
End If
Next
If bFound = True Then
'make current year pivotitem visible
.PivotItems(CStr(Year(Now()))).Visible = True
'Hide all the others
For iX = 1 To ActiveSheet.PivotTables("PivotTable1").PivotFields("Years").PivotItems.Count
Select Case ActiveSheet.PivotTables("PivotTable1").PivotFields("Years").PivotItems(iX).Name
Case CStr(Year(Now()))
'Already made visible = do nothing
Case Else
.PivotItems(iX).Visible = False 'hide it
End Select
Next
Else
MsgBox "No data for " & Year(Now()) & " is present"
GoTo End_Sub
End If
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("date1") 'date1 was the name of my date field
'I am not sure why this was not "Months"
bFound = False
For iX = 1 To ActiveSheet.PivotTables("PivotTable1").PivotFields("date1").PivotItems.Count
If ActiveSheet.PivotTables("PivotTable1").PivotFields("date1").PivotItems(iX).Name = Format(Now(), "mmm") Then
bFound = True 'Current Year data is present
Exit For
End If
Next
If bFound = True Then
'make current year pivotitem visible
.PivotItems(Format(Now(), "mmm")).Visible = True
'Hide all the others
For iX = 1 To ActiveSheet.PivotTables("PivotTable1").PivotFields("date1").PivotItems.Count
Select Case ActiveSheet.PivotTables("PivotTable1").PivotFields("date1").PivotItems(iX).Name
Case Format(Now(), "mmm")
'Already made visible = do nothing
Case Else
.PivotItems(iX).Visible = False 'hide it
End Select
Next
Else
MsgBox "No data for " & Format(Now(), "mmm") & " is present"
GoTo End_Sub
End If
End With
End_Sub:
End Sub