VBA PivotTable Filter when existing

时间:2017-06-04 23:40:35

标签: excel vba excel-vba

Hi I'm working on VBA in Excel to get my filter worked in the Pivot Table. I put a field in filter section and want to only tick "Account Invoice" and "Manual Match". Here's my code:

With wsPvtTbl.PivotTables("PivotTable1").PivotFields("Type")
        .PivotItems("Approve").Visible = False
        .PivotItems("Error").Visible = False
        .PivotItems("Interface Validation").Visible = False
        .PivotItems("Invoice Validation").Visible = False
        .PivotItems("Account Invoice").Visible = True
        .PivotItems("Manual Match").Visible = False
    End With

The problem comes up because sometimes the source data doesn't contain any "Error" item therefore there will be a bug when goes to ".PivotItems("Error").Visible = False"

Is there a way to fix it? many thanks.

1 个答案:

答案 0 :(得分:3)

这会有用吗?

....
On Error Resume Next
.PivotItems("Error").Visible = False
On Error Goto 0
....

On Error Resume Next将容忍不存在Pivot项目"错误"。所以隐藏如果它存在。之后,On Error Goto 0将重新建立正常的错误处理,以便不会跳过代码中的其他错误。

或者,您可以将这两个语句放在代码段的开头和结尾,这样任何不存在的数据透视表项都不会破坏代码。