VBA嵌套错误转到

我有应该嵌套错误检查的VBA代码,但它没有。 代码如下所示。 但是,每当在错误中发生错误(例如,错误在循环中被触发,就会发生SmallError,并且在SmallError中发生错误)。不使用第二个GoTo。 错误然后打破代码。

例如:

错误在循环中

去小错误

在SmallError错误

代码中断(这里代码应该GoTo致命错误)

Sub DoThings() On Error GoTo SmallError 'Coding Happens Do While(conditionhere) 'Looping things happen GoTo LoopResume SmallError: source = Err.source descript = Err.Description On Error GoTo Fatal Error 'Small error processing happens Resume LoopResume FatalError: source = Err.source descript = Err. Description On Error GoTo ExitError 'Fatal Error processing happens ExitError: Exit Sub LoopResume: count = count + 1 Loop On Error GoTo FatalError 'Finishing code happens End Sub 

error handling程序中不能使用On Error语句。 参见例如这篇解释这个的文章 。

你可以做的是做一个单独的例程来处理“常规错误”。 这个例程可以有一个“致命的错误”处理程序。 你的代码会看起来像这样:

(编辑:编辑代码以在发生致命错误时启用退出):

 Sub DoThings() On Error GoTo SmallError Dim fatalExit As Boolean 'Coding Happens Do While(conditionhere) 'Looping things happen LoopResume: count = count + 1 Loop On Error Goto SmallError2 'Finishing code happens Exit Sub SmallError: handleError Err.Source, Err.Description, fatalExit If fatalExit Then Exit Sub Else Resume LoopResume End If SmallError2: handleError Err.Source, Err.Description, fatalExit Exit Sub End Sub Private Sub handleError(ByVal source As String,ByVal description As String, ByRef fatalExit As Boolean) On Error Goto FatalError 'Do "small error" handling here Exit Sub FatalError: fatalExit = True 'Do "fatal error" handling here End Sub 

…你的GotoFatal Error ,而不是FatalError ,这不会让你到正确的位置…

更新您的代码到:

 On Error GoTo FatalError