如何使用数据模型遍历筛选项目并隐藏Excel数据透视表中的项目?

我一直在使用VBA中的普通数据透视表,但是最近我在数据透视表中使用了我真正喜欢的数据模型(主要是“区分计数”)发现了一些function。 我有一个正常的数据透视表中的一些代码,过滤表的logging“喜欢”一个string,它完美的作品。 如何使用数据模型将此代码转换为数据透视表?

With ActiveSheet.PivotTables("Metrics").PivotFields("Reference number") .Orientation = xlPageField .Position = 1 .EnableMultiplePageItems = True For i = 1 To .PivotItems.Count If .PivotItems(i).Name Like "*oran*" Then .PivotItems(i).Visible = False End If Next i End With 

以下是我录制macros时所创build的代码,并select要在数据模型下手动显示的项目:

 ActiveSheet.PivotTables("Metrics").PivotFields("[RawData].[Status].[Status]"). _ VisibleItemsList = Array("[RawData].[Status].&[apple_434]", _ "[RawData].[Status].&[banana_689]", _ "[RawData].[Status].&[orange_1346]", _ "[RawData].[Status].&[orange_1454]") 

这是我的方向,但我有一些麻烦访问VisibleItemsList数组:

 With ActiveSheet.PivotTables("Metrics").PivotFields("[RawData].[Status].[Status]") For i = 0 To UBound(.VisibleItemsList) If i Like "*oran*" Then i = "" Debug.Print i End If Next i End With 

输出我是数字0,1,2,3,4 – 不是文本,并且数字似乎不对应于筛选器列表中的项目数。 我不知道如何访问项目,所以我可以显示或隐藏我想要的代码。 我会诚实地说,我还没有长期与arrays工作。

我结束了使用切片机过滤数据。

 Dim sC As SlicerCache Dim sL As SlicerCacheLevel Dim aArray() As Variant 'create a slicer cache. I just used a recorded macro to get the cache code ActiveWorkbook.SlicerCaches.Add2(ActiveSheet.PivotTables("Metrics"), _ "[RawData].[Status]").Slicers.Add ActiveSheet, "[RawData].[Status].[Status]", _ "Status", "Status", 141.75, 424.5, 144, 198.75 Set sC = ActiveWorkbook.SlicerCaches("Slicer_Status") Set sL = sC.SlicerCacheLevels(1) 'this will start with the first item in the slicer With sL For i = 1 To .Count If sL.SlicerItems.Item(i).Name Like "*oran*" Then GoTo nextiteration 'this will skip over anything 'like oran when saving to the array End If ReDim Preserve aArray(0 To i) As Variant aArray(i) = sL.SlicerItems.Item(i).Name nextiteration: Next i sC.VisibleSlicerItemsList = aArray 'this set the visible items '= to the array you just created 'ActiveSheet.Shapes("Status").Visible = False 'to hide this slicer, uncomment the line above End With 

Paul te Braak撰写的这篇文章提供了大部分解决scheme。 我也用这个教程来帮助保存项目到数组。 这个stackoverflow的答案也帮助我,当我需要使用dynamic数组。 感谢-GregGalloway和-jeffreyweir:在查看您提供的链接时,我想到了使用切片器search解决scheme的想法。