Search code examples
arraysexcelvbapivotslicers

How can I select several slicer items with an array?


I am trying to select several item in a slicer for a pivot table.

I created an array with all items which should be chosen. My code only selects one item.

For cnt = UBound(Visible_Both_Years) To 0 Step -1

'filled array
MsgBox Visible_Both_Years(cnt)

'Loop through filter 
With k
    For Each l In .PivotItems
        Select Case l.Name
            Case Is = Visible_Both_Years(cnt)
                l.Visible = True
            Case Else
                l.Visible = False
        End Select
    Next

End With

I am a newbie in VBA.


Solution

  • There's no need to loop through your array, try...

    'Loop through filter
    With k
        .ClearAllFilters 'clear any existing filters
        For Each l In .PivotItems
            If IsError(Application.Match(l.Name, Visible_Both_Years, 0)) Then
                l.Visible = False
            End If
        Next
    End With
    

    Hope this helps!