VBA – GetPivotData – 无法捕获运行时错误1004

我正在编写一个程序来select一个数据透视表的一部分,并发送该提取。

一切正常,除了我一直有一个运行时错误1004 ,我不能赶上( 避免它,并保持循环 ),所以我的循环不能顺利工作…

这是有问题的部分:

On Error GoTo 0 On Error GoTo NextSale If IsError(pt.GetPivotData("Amount", Pf.Name, Pi.Name, "Sales_Opp", PiO.Name)) Then GoTo NextSale Set Rg = pt.GetPivotData("Amount", Pf.Name, Pi.Name, "Sales_Opp", PiO.Name) On Error GoTo 0 Set RgT = Union(RgT, Rg) NextSale: 

由于pt.GetPivotData("Amount", Pf.Name, Pi.Name, "Sales_Opp", PiO.Name)将引发运行时错误1004 ,当数据中不存在该组合时,我只想避免在循环中被阻塞。

我search,但没有设法解决这个… IsError()On Error GoTo不起作用。 我甚至检查了选项( 工具 – >选项 – >常规 – >错误陷印 ),我已经在Break on Unhandled Errors

以下是完整的代码:

 Sub testPt() Dim Pt As PivotTable, _ Pf As PivotField, _ Pi As PivotItem, _ PiO As PivotItem, _ Ws As Worksheet, _ TpStr As String, _ RgT As Range, _ Rg As Range Set Ws = ThisWorkbook.Sheets("PT_All") For Each Pt In Ws.PivotTables For Each Pf In Pt.PivotFields If Pf.Name <> "Sales" Then Else For Each Pi In Pf.PivotItems Set RgT = Pi.LabelRange For Each PiO In Pt.PivotFields("Sales_Opp").PivotItems On Error GoTo 0 On Error GoTo NextSale If IsError(Pt.GetPivotData("Amount", Pf.Name, Pi.Name, "Sales_Opp", PiO.Name)) Then GoTo NextSale Set Rg = Pt.GetPivotData("Amount", Pf.Name, Pi.Name, "Sales_Opp", PiO.Name) On Error GoTo 0 Set RgT = Union(RgT, Rg) NextSale: Next PiO RgT.Select MsgBox RgT.Address Next Pi End If Next Pf Next Pt End Sub 

我有一种感觉,即使是惯例,而不是第一次,这是第二次失败。
它成功地捕获了第一个错误,但是由于没有Resume xxxxxx语句,所以它仍然在尝试执行error handling。 嵌套的error handling是不允许的,所以它错误了。

摆脱On Error Goto 0行,并将剩余的On Error更改为

 On Error GoTo Err_Handlr 

然后,在结束小组之前,添加以下内容:

 Unexpected_Err: Exit Sub Err_Handlr: If err.number=1004 Resume NextSale Else Msgbox "Can't handle " & err.description Resume Unexpected_Err end if 

请注意,我正在寻找预期的错误编号 – 这意味着,如果其他部分中断,我至less可以得到通知,而不是通过任何其他可能发生的副作用失控

问题可能是与范围error handling(或缺乏)有关。

下面的代码是未经testing的,但你应该能够找出错误在哪里,并适应你的要求…

 Sub testPt() Dim Pt As PivotTable, _ Pf As PivotField, _ Pi As PivotItem, _ PiO As PivotItem, _ TpStr As String, _ RgT As Range, _ Rg As Range Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("PT_All") For Each Pt In ws.PivotTables For Each Pf In Pt.PivotFields If Pf.Name = "Sales" Then For Each Pi In Pf.PivotItems Set RgT = Pi.LabelRange For Each PiO In Pt.PivotFields("Sales_Opp").PivotItems Set Rg = Nothing On Error Resume Next Set Rg = Pt.GetPivotData("Amount", Pf.Name, Pi.Name, "Sales_Opp", PiO.Name) On Error GoTo 0 If Not RgT Is Nothing Then If Not Rg Is Nothing Then Set RgT = Union(RgT, Rg) Else: If Not Rg Is Nothing Then Set RgT = Rg End If Next PiO Next Pi End If Next Pf Next Pt If Not RgT Is Nothing Then RgT.Select MsgBox RgT.Address Else: MsgBox "RgT is empty" End If End Sub