VBA 错误处理程序 - 在退出子之前需要错误 GoTo 0?



>我有下面的代码,我想知道如果它只是要退出sub,是否需要"出错时GoTo 0"。 我可以省略那行吗?

很抱歉新手问题,提前感谢您。


Sub LookForNAs
'some var declarations
'some lengthy code
On Error GoTo ErrorHandler:
pt_nca.PivotFields("Group").CurrentPage = "#N/A"
On Error GoTo 0
'some other lengthy code
ErrorHandler:
If Err.Number = 1004 Then
MsgBox "No #N/As found in the pivot table."
End If
Call TurnOnStuff
On Error GoTo 0
Exit Sub
End Sub

我会按如下方式编写您的代码。 我还对@Freeflow给出的答案使用变体 - 在检查工作表是否存在并在不存在时创建它时很有用。处理这样的每个可能的错误需要做很多工作 - 尤其是你不期望的错误。

Sub LookForNAs()
'some var declarations
On Error GoTo ErrorHandler
'some lengthy code
pt_nca.PivotFields("Group").CurrentPage = "#N/A"
'some other lengthy code
Fast_Exit:
TurnOnStuff
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 1004
MsgBox "No #N/As found in the pivot table.", vbOKOnly + vbCritical, Err.Number
Resume Fast_Exit
Case 6
MsgBox "Overflow error.", vbOKOnly + vbCritical, Err.Number
Resume Fast_Exit
Case Else 'Catch any unhandled errors.
MsgBox Err.Description, vbOKOnly + vbCritical, Err.Number
Resume Fast_Exit
End Select
End Sub

另一种方法是将测试错误封装到一个函数中,该函数可帮助您将"快乐路径"与"错误路径"分开

Public Sub CallerForLookForNAs()
If TryLookForNAs Then Exit Sub
'etc 
End Sub
Public Function TryLookForNAs() As Boolean
TryLookForNAs = False
On Error Resume Next
pt_nca.PivotFields("Group").CurrentPage = "#N/A"
TryLookForNAs = Err.Number > 0
On Error GoTo 0
End Function

这种通用方法在 =Rubberduck 博客 https://rubberduckvba.wordpress.com/2019/05/中有更详细的讨论

所以我省略了错误时转到 0,下面的内容是否可以接受或不正确?

Sub LookForNAs()
'some code
On Error GoTo ErrorHandler:
pt_nca.PivotFields("Group").CurrentPage = "#N/A"
On Error GoTo 0
' some other code
ErrorHandler:
If Err.Number = 1004 Then
MsgBox "No #N/As found in the pivot table."
Call TurnOnStuff
Exit Sub
End If
'placeholders for other err.numbers
'If Err.Number = blah blah blah
End Sub

对象 Err 包含错误的编号。问题是,如果在出现错误时省略有问题的行,执行将阻塞。因此,如果出现错误,该行会告诉 VBA 转到您的命名块。如果省略,它将起作用,但是当错误上升时,程序将停止。希望这能澄清。

最新更新