我在从数据透视表中的过滤器中删除一个选项时遇到问题,如果我录制一个宏并尝试应用只删除了~20个选项中的一个的更改,Excel会弹出一条消息:
线路延续太多了!
似乎它试图按名称声明每个可能的过滤器选项,就像这里:
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Product Component].[(c) Segment 4].[(c) Segment 4]").VisibleItemsList = Array _
("[Product Component].[(c) Segment 4].&[31558]", _
"[Product Component].[(c) Segment 4].&[315516]", _
"[Product Component].[(c) Segment 4].&[3152027]", _
"[Product Component].[(c) Segment 4].&[3152028]")
是否可以只删除一个选项并用一个命令显示其余的~20
答案 0 :(得分:2)
Great question. Because this is an OLAP PivotTable, the key is to set the PivotField's CubeField.IncludeNewItemsInFilter Property to either TRUE or FALSE depending on what you want to do. See https://msdn.microsoft.com/en-us/vba/excel-vba/articles/pivotfield-includenewitemsinfilter-property-excel
Let's say we're interested in these two items:
If you want only those two things to be visible, set the PivotField's CubeField.IncludeNewItemsInFilter Property to FALSE, and then feed an array of things that should be visible to pf.VisibleItemsList, like this:
Sub ShowOLAPItems()
'
Dim pt As PivotTable
Dim pf As PivotField
Set pt = ActiveSheet.PivotTables("PivotTable1")
Set pf = pt.PivotFields("[Product Component].[(c) Segment 4].[(c) Segment 4]")
pf.CubeField.IncludeNewItemsInFilter = FALSE 'This is the default property
pf.VisibleItemsList = Array("[Product Component].[(c) Segment 4].&[31558]", _
"[Product Component].[(c) Segment 4].&[315516]")
End Sub
If you want everything except those two things to be visible, set the PivotField's CubeField.IncludeNewItemsInFilter Property to TRUE, and then feed an array of things that should be visible to pf.HidenItemsList, like this:
Sub HideOLAPItems()
'
Dim pt As PivotTable
Dim pf As PivotField
Set pt = ActiveSheet.PivotTables("PivotTable1")
Set pf = pt.PivotFields("[Product Component].[(c) Segment 4].[(c) Segment 4]")
pf.CubeField.IncludeNewItemsInFilter = TRUE
pf.HiddenItemsList = Array("[Product Component].[(c) Segment 4].&[31558]", _
"[Product Component].[(c) Segment 4].&[315516]")
End Sub
答案 1 :(得分:0)
如果您只想从过滤器中删除一个项目,请执行以下操作:
Dim Table as PivotTable
Set PivotTable = YourPivotTable
Dim Field as PivotField
Set Field = Table.PivotFields("YourFieldName")
With Field
.EnableMultiplePageItems = True
.ClearAllFilters
End With
Field.PivotItems("YourItemName").Visible = False
由于清除所有过滤器意味着所有项目都可见,我们可以逐个删除每个项目。
值得注意的是,如果你这么做很多,你应该设置Table.ManualUpdate = False
直到完成更改过滤器,然后{I}完成后Table.ManualUpdate = True
。这将阻止每次过滤器更改时更新(这可能非常耗时)。
编辑:如果您必须传递数组,那么只需构建一个数组:
Dim ItemToHide as String
ItemToHide = "YourItemToHide"
' Assumes only one is being hidden
Dim VisibleItems(1 to Field.PivotItems.Count - 1) as Variant
Dim Item as PivotItem
For each Item in Field.PivotItems
If Item.Value <> ItemToHide Then
Dim Count as Long
Count = Count + 1
VisibleItems(Count) = Item.Value
End If
Next
Table.VisibleItemsList = VisibleItems