JoeS
JoeS

Reputation: 23

Filtering Pivot Slicer using a range of values

I have a pivot table that is filtered by a date filed pivot slicer. On another sheet i have a 12 month date range example from cell A1:A12. I have code that loops through the slicer and tries to match whats in the slicer compared to the range. Ideally i would want the slicer to then only select the values that exist within the range A1:A12. The code below runs but selected everything once the loop has terminated.

Any ideas?

Sub DateSelect()

Dim ws As Worksheet
Dim i As Integer, iLookupColumn As Integer
Dim sl As SlicerCache
Dim sDate As String
Set sl = ThisWorkbook.SlicerCaches("Slicer_Month_and_Year")

Set ws = ThisWorkbook.Sheets("Macro")
For i = 1 To sl.SlicerItems.Count
    sDate = sl.SlicerItems(i).Name
    If IsError(Application.Match(sDate, ws.Range(ws.Cells(1, 14), ws.Cells(13, 14)), 0)) Then
        ThisWorkbook.SlicerCaches("Slicer_Month_and_Year").SlicerItems(i).Selected = False
    Else
        ThisWorkbook.SlicerCaches("Slicer_Month_and_Year").SlicerItems(i).Selected = True
    End If
Next i


End Sub 

Upvotes: 0

Views: 1804

Answers (1)

Damian
Damian

Reputation: 5174

This should work:

Option Explicit
Sub filterSlicers()

    Dim i As Long, SI As SlicerItem, SC As SlicerCache, PvT As PivotTable, C As Range, Cell As Range, ws As Worksheet
    Dim DictFilter As Scripting.Dictionary 'You need Microsoft Scripting Runtime for this to work

    For Each PvT In ThisWorkbook.Sheets("TheSheetContainingThePivotTables").PivotTables 'this will improve a lot the performance
        PvT.ManualUpdate = True
    Next PvT

    Set ws = ThisWorkbook.Sheets("Macro")
    Set C = ws.Range("A1:A12")  'change your range

    Set DictFilter = New Scripting.Dictionary 'initialize the dictionary
    For Each Cell In C
        DictFilter.Add Cell.Value, 1 'store the values you want  to filter on the dictionary
    Next Cell


    Set SC = ThisWorkbook.SlicerCaches("Slicer_Month_and_Year")
    SC.ClearAllFilters
    For Each SI In SC.VisibleSlicerItems
        Set SI = SC.SlicerItems(SI.Name)
        If DictFilter.Exists(SI.Name) Then
            SI.Selected = True
        Else
            SI.Selected = False
        End If
    Next

    For Each PvT In ThisWorkbook.Sheets("TheSheetContainingThePivotTables").PivotTables 'return the automatic update to the pivot tables
        PvT.ManualUpdate = False
    Next PvT

End Sub

Note that I've add some extra code for performance (turning off the manual update for the pivot tables that are using the slicer)

Upvotes: 1

Related Questions