【发布时间】:2018-03-26 18:05:56
【问题描述】:
我的代码可以遍历我的数据透视表中的每个 PivotItem。我在下面显示的代码是一种更加手动的方法。我的循环将 PivotItem 保存在数据透视表中显示的内容之外,因为数据透视表上有一个过滤器来限制事物。因此,假设我使用.PivotItems("BMR"),并且代码工作正常,因为在数据透视表中显示了 BMR PivotItems。但是,如果我执行.PivotItems("EHFG"),它将出错,因为它不在数据透视表中,因为它正在被过滤掉。
如何调整我的代码,使其不会在不存在的数据透视项上中断?如果 With 语句不存在,也许可以跳过它?
Option Explicit
Sub test()
Dim PvtTbl As PivotTable
Dim columnsDifference As Long
Dim PvtFld As PivotField
Set PvtTbl = Sheets("NIR Pivot").PivotTables("NIR_Pivot")
Set PvtFld = PvtTbl.PivotFields("Prod. Code")
PvtFld.PivotItems("EHFG").ShowDetail = True 'Show pivot item
columnsDifference = PvtTbl.TableRange2.Columns.Count - PvtTbl.DataBodyRange.Columns.Count
With PvtTbl.PivotFields("Prod. Code").PivotItems("EHFG").DataRange **ERRORS HERE
' Debug.Print .Offset(, -columnsDifference).Resize(.Rows.Count, .Columns.Count + columnsDifference).Address
.Offset(, -columnsDifference).Resize(.Rows.Count, .Columns.Count + columnsDifference).Select
End With
End Sub
【问题讨论】: