如何在Excel VBA中显示多个PivotItems
我在工作表“主”中有一个数据透视表。 在PivotField
“报表filter”中,我有“国家代码”,其中包含200个国家。 我想使用InputBox从该filter中显示多个国家/地区。
问题是我需要手动select最小的一个国家或所有的filter,并运行这个程序。 我不能通过这样做得到正确的数据。 我需要取消select所有的国家,然后我需要运行。
我的代码
Sub Addcountries() Dim ws As Worksheet Dim str1 As Variant Dim Data As Variant Dim pf As PivotField Dim target As PivotTable Set ws = Sheets("Main") str1 = Application.InputBox("Enter the Country - comma separated") If str1 = False Then MsgBox "Please Enter one Country", , "Filter Country" Exit Sub Else If InStr(1, str1, ",") > 0 Then Data = Split(str1, ",") For i = LBound(Data) To UBound(Data) ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(Data(i)).Visible = True Next i Else ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(str1).Visible = True End If End If End Sub
您可以循环PivotItems
集合,并检查每个PivotItem.Name
是否与Data
数组中的某个选定的Data
Match
– 您可以使用Match
function来完成该function。
码
If str1 = False Then MsgBox "Please Enter one Country", , "Filter Country" Exit Sub Else If InStr(1, str1, ",") > 0 Then ' more than 1 country >> create array Data = Split(str1, ",") Else ' single country Data = Array(str1) '<-- create array with 1 element (for Match to work) End If ' === You need a different loop, loop through all Pivot-Items, then look for a match with Data (array) === Dim pi As PivotItem ' clear previous Filter ws.PivotTables("MainTable").PivotFields("Country Code").ClearAllFilters For Each pi In ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems ' check if current Pivot-Item equals one of the elements of the array (use Match function) If Not IsError(Application.Match(pi.Name, Data, 0)) Then ' Match successful pi.Visible = True Else pi.Visible = False End If Next pi End If ' rest of your code
为了让你的filter工作,你需要给你不想看到的Pivot Items的False Visible值,以及给你所做的那个True Value,以便你将所有的Pivot Items设置为True或False。
这里有一些代码给你一个想法;
Sub Addcountries() Dim ws As Worksheet Dim str1 As Variant Dim Data() As Variant Dim pf As PivotField Dim target As PivotTable Dim PivotItem As Object Dim ShowMe As Boolean Set ws = Sheets("Main") str1 = Application.InputBox("Enter the Country - comma separated") If str1 = False Then MsgBox "Please Enter one Country", , "Filter Country" Exit Sub Else If InStr(1, str1, ",") > 0 Then Data = Split(str1, ",") Else 'Make Single Item Array ReDim Data(1) Data(0) = str1 End If For Each PivotItem In ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems 'Default Visibility Is False ShowMe = False For i = LBound(Data) To UBound(Data) 'Loop Through Each Item In Data To See If You Should ShowMe ShowMe = (PivotItem.Name = Data(i)) If ShowMe Then 'Quit Early If You ShowMe Exit For End If Next i PivotItem.Visible = ShowMe Next PivotItem End If End Sub