VBA 嵌套在错误 GoTo 上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15811713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Nested On Error GoTo
提问by steventnorris
I have VBA code that is supposed to be nested error checking, but it does not. The code is psuedo as below. However, whenever an error occurs within an error (For instance, an error is tripped in the loop, goto SmallError occurs, and an error occurs in SmallError) The second GoTo is not used. The error then breaks the code.
我有应该进行嵌套错误检查的 VBA 代码,但事实并非如此。代码如下所示。但是,每当错误中发生错误时(例如,错误在循环中跳闸,发生 goto SmallError,在 SmallError 中发生错误)不使用第二个 GoTo。然后错误会破坏代码。
Ex:
前任:
Error in Loop
循环错误
GoTo SmallError
转到小错误
Error in SmallError
SmallError 中的错误
Code Breaks (Here code should GoTo FatalError)
代码中断(这里的代码应该 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
采纳答案by GTG
You can't use an On Error statement within an error handler. See e.g. this article that explains this.
您不能在错误处理程序中使用 On Error 语句。参见例如解释这一点的这篇文章。
What you CAN do however is to have a separate routine that handles the "regular error". This routine can have a "fatal error" handler. Your code would then look something like this:
但是,您可以做的是拥有一个单独的例程来处理“常规错误”。这个例程可以有一个“致命错误”处理程序。您的代码将如下所示:
(Edit: Edited the code to enable exit when there is a fatal 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
回答by John Bustos
... you have Fatal Error
in your Goto
rather than FatalError
, that won't get you to the right location...
... 你有Fatal Error
你的Goto
而不是FatalError
,那不会让你到正确的位置......
Update your code to:
将您的代码更新为:
On Error GoTo FatalError