我正在尝试使用多个条件过滤数据透视表。我检查了其他posts,但是我收到错误" Range类的AutoFiler方法失败"跑步时:
Range("g41").Select
Selection.AutoFilter field:=1, Criteria1:=Array( _
"101", "103"), Operator:=xlFilterValues
以下作品,但有很多项目要过滤真/假
With ActiveSheet.PivotTables("PivotTable3").PivotFields("Value")
.PivotItems("101").Visible = True
.PivotItems("103").Visible = True
.PivotItems("105").Visible = False
End With
有更有效的方法吗?
答案 0 :(得分:8)
您可以尝试以下代码:
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
答案 1 :(得分:0)
这些问题的解决方法非常简单。
只需使用一种方法即可通过“ SLICER”(和VBA代码)选择项目。
有关更多详细信息,请使用记录宏选项。
代码示例
ActiveWorkbook.SlicerCaches(“ Slicer_RS_YM”)。SlicerItems(“ Item1Name”)。Selected = True‘include ActiveWorkbook.SlicerCaches(“ Slicer_RS_YM”)。SlicerItems(“ Item2Name”)。Selected = False‘排除
答案 2 :(得分:0)
我只是在尝试做类似的事情,但由于无法调整可见度而出现错误。
PTItm.Visible = False
研究它与某种查询有关(我认为不是OLAP,或者可能是因为我将数据透视表设置为表视图)。无论如何,我不得不稍微调整一下Shai的好主意,以使其发挥作用。我以为可以与他人分享,以免其他人将来遇到这个线程,有时会摆弄一些奇怪的错误。关键是使用另一个数组和.VisibleItemsList。
Sub FilterPivotItems()
Dim PT As PivotTable
Dim PTItm As PivotItem
Dim FiterArr() As Variant
Dim NewFilterList() As Variant
ReDim Preserve NewFilterList(0) 'I still haven't figured out how to avoid this double dim'ing, sorry
' use an array to select the items in the pivot filter you want to keep visible
FiterArr = Array("[POSched].[Inspection Plan].&", "[POSched].[Inspection Plan].&[DEFAULT]") '2 Items here, the first one means empty i.e. ""
' set the Pivot Table
Set PT = ThisWorkbook.Sheets("Prisma").PivotTables("SequenceOverview")
' loop through all Pivot Items in "Value" Pivot field
For Each PTItm In PT.PivotFields("[POSched].[Inspection Plan].[Inspection Plan]").PivotItems
If IsError(Application.Match(PTItm.Value, FiterArr, 0)) Then ' check if current item is not in the filter array
NewFilterList(UBound(NewFilterList)) = PTItm.Value 'Make a new array to use later
ReDim Preserve NewFilterList(UBound(NewFilterList) + 1)
End If
Next PTItm
ThisWorkbook.Sheets("Prisma").PivotTables("SequenceOverview").PivotFields("[POSched].[Inspection Plan].[Inspection Plan]").VisibleItemsList = NewFilterList
End Sub
编辑:我忘了提及此代码,假定之前未应用任何过滤器。这对我来说很好,但可能对所有人都没有帮助。