使用VBA中的值过滤数据透视表

时间:2017-09-21 11:57:18

标签: vba excel-vba pivot-table excel

我试图从数组中过滤数据透视表列(GP#)(在此示例中缩写)。

过滤器确实有效,但当我找到一个不在过滤器中的数字(在这种情况下为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

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

1 个答案:

答案 0 :(得分:1)

尝试使用以下代码查找您使用名为PivotField的{​​{1}}中是否找到某个数组元素。

GP#