VBA嵌套在错误GoTo上

时间:2013-04-04 12:50:00

标签: excel vba error-handling nested goto

我有VBA代码应该是嵌套的错误检查,但事实并非如此。该代码如下所示。但是,每当错误中发生错误时(例如,错误在循环中跳闸,发生goto SmallError,并且SmallError中发生错误)不使用第二个GoTo。然后错误会破坏代码。

例如:

循环错误

GoTo SmallError

SmallError错误

代码中断(此处代码应为GoTo FatalError)

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

2 个答案:

答案 0 :(得分:4)

您不能在错误处理程序中使用On Error语句。参见例如这article that explains this

但是,您可以使用单独的例程来处理“常规错误”。此例程可能具有“致命错误”处理程序。您的代码看起来像这样:

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

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

答案 1 :(得分:0)

...您的Fatal Error而不是Goto中有FatalError,这不会让您到达正确的位置......

将您的代码更新为:

On Error GoTo FatalError