使用通配符过滤一个数据透视表而不进行迭代

我想设置报告filter,所以一个数据透视表将只包含一个使用通配符的单词。

例如,Excel透视行(VBA中的xlRowField)可以使用PivotFilters.Add2进行过滤,

ActiveSheet.PivotTables("PivotTable1").PivotFields("RowField").PivotFilters.Add2 _ Type:=xlCaptionContains, Value1:="this" 

但我需要过滤报告f(xlPageField在VBA中)。 我知道我可以迭代pivotitems:

 For i = 1 To PivotItems.Count If PivotItems(i) Like "*this*" Then PivotItems(i).Visible = true else PivotItems(i).Visible = false End If next 

但是我正在谈论的是一个非常大的数据集,在这个数据集中迭代需要花费很长时间,而GUI过滤只需要一秒钟的时间:

在这里输入图像说明 在这里输入图像说明

我试图将一个GUI过滤logging到一个macros中,事实certificate,Excel只是logging了一个手动过滤,就好像我手动去了每个项目并检查它。

演示数据集

 ---------------------------- | Name | Class | Grade | ---------------------------- | Joe | B1 | 100 | ---------------------------- | Steve | B2 | 80 | ---------------------------- | Rebecca | C | 99 | ---------------------------- | Sharon | D | 78 | ---------------------------- 

您可以将其下载为CSV格式:

 Name,Class,Grade Joe,B1,100 Steve,B2,80 Rebecca,C,99 Sharon,D,78 

演示枢轴

 ------------------------------------- | Class | (Multiple Items) eg B* | How do I do it without iteration? ------------------------------------- --------------------------------- | Row Labels | Sum of Grade | --------------------------------- | Joe | 100 | --------------------------------- | Steve | 80 | --------------------------------- | Grand Total | 180 | --------------------------------- 

也许这会更快(虽然我没有在一个大的数据集上testing它)。

在某个表格上创build一个名为“searchText”的范围。

在数据集的末尾放置一个名为“helper”的列。

把公式:

  =NOT(ISERROR(SEARCH(searchText,B2))) 

在你的帮手列中,B代表你正在search的数据。

使用此代码:

 Dim shtSearch As Worksheet Dim shtPivot As Worksheet Dim myPivot As PivotTable Dim helperPF As PivotField Set shtSearch = Sheets("Sheet1") shtSearch.Range("searchText").Value = "b" 'put in whatever you are searching for. Set shtPivot = Sheets("Sheet4") Set myPivot = shtPivot.PivotTables("myPivot") Set helperPF = myPivot.PivotFields("helper") With helperPF .Orientation = xlPageField .Position = 1 End With helperPF.CurrentPage = "TRUE" myPivot.PivotCache.Refresh