2017-09-21 81 views
0

我试图从数组中过滤数据透视表列(GP#)(在本例中缩写)。使用VBA中的值过滤数据透视表

过滤器的工作,但我得到一个数(在这种情况下83292)不是在过滤器后,Excel与错误崩溃:

运行时错误1004应用程序定义或对象 - 定义的错误

有没有一种方法来检查数字/名称等是否在过滤器中,如果它然后适用于过滤器?

我的代码

vGP = Array("83041", "83327", "83292") 
ActiveSheet.PivotTables("PivotTable1").ManualUpdate = True 
With ActiveSheet.PivotTables("PivotTable1").PivotFields("GP#") 
    .PivotItems(1).Visible = True 

    ' below code ensure pivot table filter does not cause error by not having anything in the filter 

    For i = 2 To .PivotItems.Count 
     .PivotItems(i).Visible = False 
     If .PivotItems(i).Visible Then .PivotItems(i).Visible = False 
    Next i 

    ' goes through array and adds any value in array 
    For Each i In vGP 
     .PivotItems(i).Visible = True 
    Next i 
    On Error GoTo 0 

任何人都可以请帮助确保数组中的值可以被添加到过滤器和值数组中不存在数据透视表中被忽略

+0

所以这个问题似乎是问同样的事情作为你前面的问题在https://stackoverflow.com/questions/45718045/pivotfields-multiple-filter/45726720#45726720我已经回答了一些非常高效的代码。 – jeffreyweir

+0

此外,上面的代码中有多个设计缺陷,我都是用原始答案编写的。 'If .PivotItems(i).Visible Then .PivotItems(i).Visible = False'这一行是完全多余的,下一个循环需要包含在“On Error Resume Next”中。如果您完全忽视了以前完美运作的答案,我们回答您的问题的重点是什么? – jeffreyweir

回答

0

尝试使用下面的代码来查找在PivotField内是否存在使用名为GP#的某个数组元素。

Dim PvtTbl As PivotTable 
Dim PvtFld As PivotField 
Dim MatchFound As Boolean, i As Long 

' set the Pivot Table 
Set PvtTbl = ActiveSheet.PivotTables("PivotTable1") 

' set the Pivot Field 
Set PvtFld = PvtTbl.PivotFields("GP#") 

MatchFound = False ' reset flag 
For i = 1 To PvtFld.PivotItems.Count ' loop through all pivot items 
    If PvtFld.PivotItems(i).Name = vGP(1) Then ' check if the second array element is found in one of the Pivot items 
     MatchFound = True ' raisw flag 
     Exit For 
    End If 
Next i 

If MatchFound Then 
    PvtFld.PivotItems(i).Visible = True ' apply filter if the array element found 
End If 
相关问题