如何仅在数据透视表项存在时禁用它?

时间:2018-10-19 09:33:33

标签: excel vba excel-vba

在下面的代码中,如果不存在这样的枢轴项,则行.PivotItems("Central Events").Visible = False将引发错误,因此,我目前忽略了On Error Resume Next的错误:

With BA_view_pivots_sheet.PivotTables("Corporate & Investment Banking").PivotFields( _
        "Market")
        On Error Resume Next ' ignore error when projects for Central Events does not exist
            .PivotItems("Central Events").Visible = False
        On Error GoTo 0
End With

但是,我不想忽略该错误,而是想执行检查是否存在这种枢轴项并仅在这种情况下将其禁用。所以我想出了类似的方法,但是显然不起作用,因为该对象不存在:

With BA_view_pivots_sheet.PivotTables("Corporate & Investment Banking").PivotFields( _
        "Market")
        If Not .PivotItems("Central Events") Is Nothing then
            .PivotItems("Central Events").Visible = False
        End if
End With

除了像在我的第一个代码片段中那样忽略它之外,还有其他方法可以解决这个可能的错误吗?

1 个答案:

答案 0 :(得分:0)

我认为您需要这样的东西:

Dim pt As PivotTable, pivot_item As PivotItem
For Each pt In BA_view_pivots_sheet.PivotTables
    If pt.Name = "Corporate & Investment Banking" Then 'check that pivot name exists
        For Each pivot_item In pt.PivotFields("Market").PivotItems
            If pivot_item.Name = "Central Events" Then  'check that item name exists
                pivot_item.Visible = False: Exit For
            End If
        Next pivot_item: Exit For
    End If
Next pt