Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA - Pivot table filter multiple criteria

Tags:

excel

vba

I am trying to filter a pivot table with multiple criteria. I've check other posts, but I am getting the error

AutoFiler method of Range class failed

when running:

Range("g41").Select
Selection.AutoFilter field:=1, Criteria1:=Array( _
    "101", "103"), Operator:=xlFilterValues

The following works, but there are quite a long number of items to filter true/false

With ActiveSheet.PivotTables("PivotTable3").PivotFields("Value")
    .PivotItems("101").Visible = True
    .PivotItems("103").Visible = True
    .PivotItems("105").Visible = False
End With

Is there a more effective way?

like image 982
Selrac Avatar asked Feb 28 '17 10:02

Selrac


Video Answer


1 Answers

You can try the code below:

Option Explicit

Sub FilterPivotItems()

Dim PT          As PivotTable
Dim PTItm       As PivotItem
Dim FiterArr()  As Variant

' use an array to select the items in the pivot filter you want to keep visible
FiterArr = Array("101", "105", "107")

' set the Pivot Table
Set PT = ActiveSheet.PivotTables("PivotTable3")

' loop through all Pivot Items in "Value" Pivot field
For Each PTItm In PT.PivotFields("Value").PivotItems
    If Not IsError(Application.Match(PTItm.Caption, FiterArr, 0)) Then ' check if current item is not in the filter array
        PTItm.Visible = True
    Else
        PTItm.Visible = False
    End If
Next PTItm

End Sub
like image 79
Shai Rado Avatar answered Sep 20 '22 00:09

Shai Rado