How to set default filters for a PivotTable using VBA?

Setting default filters for a PivotTable using VBA can be a useful way to automate the setup of your data analysis. Here’s a general guide on how you can do this in Excel using VBA:

Sub SetPivotTableDefaultFilters()
    Dim ws As Worksheet
    Dim pt As PivotTable
    Dim pi As PivotItem
    Dim pf As PivotField
    
    ' Set the worksheet and PivotTable names
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change to your sheet name
    Set pt = ws.PivotTables("PivotTable1") ' Change to your PivotTable name
    
    ' Set filter for a specific field
    Set pf = pt.PivotFields("FieldName") ' Change to your PivotTable field name
    
    ' Clear all filters first (optional)
    pf.ClearAllFilters 

    ' Loop through each PivotItem in the PivotField and set visibility
    For Each pi In pf.PivotItems
        ' Check the condition for default filters
        If pi.Name = "YourCriteria" Then ' Replace with your criteria
            pi.Visible = True
        Else
            pi.Visible = False
        End If
    Next pi
End Sub
  • Open the VBA Editor: Press `ALT + F11` to open the VBA editor in Excel.
  • Insert a New Module: Click on `Insert` in the menu and then select `Module`. This creates a new module where you can write your VBA code.
  • Write the VBA Code: Use the following template code to set default filters for your PivotTable. You will need to modify the code to match your specific worksheet, PivotTable, and filter criteria.
  • Customize the Code: Change the following placeholders to match your specific setup:
    • `”Sheet1″`: The name of the worksheet containing your PivotTable.
    • `”PivotTable1″`: The name of your PivotTable.
    • `”FieldName”`: The name of the field you want to filter.
    • `”YourCriteria”`: The specific criteria you want to set as the default filter.
  • Run the Macro: Close the VBA editor. In Excel, go to the `Developer` tab, click on `Macros`, select `SetPivotTableDefaultFilters`, and run it.

This code clears any existing filters on the specified field and then sets the visibility of items in that field based on your criteria. Adjust it to fit the logic you need for your specific case. If you’re dealing with multiple fields or more complex criteria, you’ll need to add additional logic and loops accordingly.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project