在下面的代码中,行 .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
除了像我的第一个代码片段那样忽略它之外,还有其他方法可以解决这个可能的错误吗?
最佳答案
我认为你需要这样的东西:
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
关于excel - 如何仅在存在时禁用数据透视项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52889650/