martinctc
10/24/2016 - 11:57 AM

Filter all pivot tables on the same worksheet

Filter all pivot tables on the same worksheet

Private Sub CommandButton1_Click()

Dim month_a, month_b, month_c, j As Integer
Dim currentm, defaultm As Long
Dim pvt As PivotTable
Dim coll As Collection
Dim PivotRefs, i As Variant

Application.ScreenUpdating = False

On Error Resume Next

'Identify all PivotTables within active worksheet and transform into an array

Set coll = New Collection

For Each pvt In ActiveSheet.PivotTables

coll.Add pvt.Name

Next

ReDim PivotRefs(0 To coll.Count - 1)

For j = 1 To coll.Count
        PivotRefs(j - 1) = coll.Item(j)
Next

'Start collecting data on what you wish to filter

currentm = Application.InputBox(prompt:="I'd like to check whether you're a robot. How many months have this project been running since January 2014?", Type:=1)

month_a = Application.InputBox(prompt:="Enter the first month you'd like to filter by", Type:=1)

month_b = Application.InputBox(prompt:="Enter the second month you'd like to filter by (Click 'cancel' if none)", Type:=1)

month_c = Application.InputBox(prompt:="Enter the third month you'd like to filter by (Click 'cancel' if none)", Type:=1)

defaultm = 1
 
'Uncheck every filter
 
For i = 0 To coll.Count - 1
    For defaultm = 1 To currentm
        ActiveSheet.PivotTables(PivotRefs(i)).PivotFields("MONTH").PivotItems(defaultm).Visible = False
    Next defaultm
Next i

'Debugging Area

For i = 0 To coll.Count - 1
    Debug.Print PivotRefs(i)
Next i

Debug.Print coll.Count

'Check required filter
For i = 0 To coll.Count - 1
    With ActiveSheet.PivotTables(PivotRefs(i)).PivotFields("MONTH")
        .PivotItems(month_a).Visible = True
        .PivotItems(month_b).Visible = True
        .PivotItems(month_c).Visible = True
    End With
Next i
End Sub