2017-09-21 78 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 
相關問題