Home > OS >  Adjust filters of a Pivot Table VBA
Adjust filters of a Pivot Table VBA

Time:05-26

I am trying to create a Macro attached to a button that will adjust the filters of a pivot table based on predetermined settings. I want to clear all the pivot table filters first select the filters I want. The code below gives me Run-time error '1004': Unable to set the PivotItems property of the PivotField class. It also doesn't clear the filter on the Pivot Table

    Sub PC()

'code for WHS1
Worksheets("Multi_WHS_Pivot").Activate
ActiveSheet.PivotTables("Table").PivotFields("Branch").CurrentPage = "(All)"
With ActiveSheet.PivotTables("Table").PivotFields("Branch")
    .ClearAllFilters
    .EnableMultiplePageItems = True
    .PivotItems("015") = True
    .PivotItems("716") = True
    .PivotItems("710") = True
End With
Worksheets("Main Data").Activate
End Sub

Many thanks to anyone who can help

CodePudding user response:

I haven't tested it, but I have amended your macro so that it loops through each pivot item. For each pivot item, if the name doesn't equal "015", "716", or "710", the visible property is set to False.

Sub PC()
    
    Dim currentPivotItem As PivotItem

    'code for WHS1
    With Worksheets("Multi_WHS_Pivot").PivotTables("Table").PivotFields("Branch")
        .ClearAllFilters
        .EnableMultiplePageItems = True
        For Each currentPivotItem In .PivotItems
            If IsError(Application.Match(currentPivotItem.Name, Array("015", "716", "710"), 0)) Then
                currentPivotItem.Visible = False
            End If
        Next currentPivotItem
    End With
    
    Worksheets("Main Data").Activate
    
End Sub
  • Related