我正在尝试使用多个条件过滤数据透视表。我检查了其他posts,但是在运行时出现错误“Range类的AutoFiler方法失败”:

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

以下工作正常,但有很多项目要过滤true/false
With ActiveSheet.PivotTables("PivotTable3").PivotFields("Value")
    .PivotItems("101").Visible = True
    .PivotItems("103").Visible = True
    .PivotItems("105").Visible = False
End With

有没有更有效的方法?

最佳答案

您可以尝试以下代码:

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

10-07 21:36