VBA – Automated Pivot Filtering

Pivot tables are one of the most powerful tools in Excel for summarizing and analyzing data. No doubt about it. However, sometimes you need to go beyond their built-in functionality. In this article, we will explore how to use VBA to dynamically filter a pivot table based on user selections from a slicer. This technique is particularly useful when you want to sync filters across multiple pivot tables or automate repetitive tasks. It can actually save hours of work and days of explanations.

We will use a real-world example involving English football (soccer) teams and their trophies over the last 11 years. So, imagine the following nice task in 3 points:

  1. Allow users to select teams using a slicer.
  2. Record the selected teams in a temporary table.
  3. Filter a second pivot table to show only the selected teams.

Filtering is based on the football (soccer) teams that won an English Premier League in the last 11 years.

 

This is the second table, that is actually being filtered, based on the first one.

This process can be tedious if done manually, but with VBA, it becomes quick and efficient. The proposed solution in the article (and also implemented in the YouTube video) is the following:

  1. Extracting Selected Slicer Items: Record the selected teams in a temporary table.
  2. Filtering the Pivot Table: Dynamically filter the pivot table based on the recorded selections.
  3. Helper Functions: Ensure the code is robust and error-free.

The code and the explanations are below:

How It Works

  • The code loops through each item in the slicer (Slicer_Team).
  • Selected items are recorded in Column A of the tblTemp sheet and highlighted in green.
  • Unselected items are recorded in Column B and highlighted in yellow.
  • The temporary table is cleared before each run to ensure fresh data.
  • Once the selected teams are recorded, we go to the next step, filtering the pivot dynamically

How They Work

  • IsInRange: Loops through a range and checks if a specific value exists.
  • LastRow: Finds the last non-empty row in a specified column.

The whole Excel file is in GitHub and the YouTube video is below!

Enjoy it!

Tagged with: , , , , ,