Home » excel » excel – VBA code that clears filter on pivot table on exit of worksheet

excel – VBA code that clears filter on pivot table on exit of worksheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to clear a pivot table filter on exit of that sheet.

I’ve googled and found nothing that works or is similar to what I’m trying to do.

Private Sub Worksheet_deactivate()

    Call ClearFilter

End Sub

Sub ClearFilter()

' ClearFilter Macro

    ActiveSheet.PivotTables("PivotTable1").PivotFields( _
        "[DIM Material Master].[Material Group].[Material Group]").ClearAllFilters
End Sub

When I run it I get a Run-time error 1004, Unable to get the PivotTables property of the Worksheet class.

How to&Answers:

If you’ve deactivated the sheet, then it’s no longer the ActiveSheet. Change ActiveSheet to ThisWorkbook.Worksheets("yoursheetname") to reference the worksheet the pivot table in question is on.

Another option is a bit simpler:

Private Sub Worksheet_deactivate()

    Me.PivotTables("PivotTable1").PivotFields( _
        "[DIM Material Master].[Material Group].[Material Group]").ClearAllFilters

End Sub