您的代码运行正常。处理错误的代码应该写在主过程之外,记住你的代码也应该尝试发现潜在的错误并在它们导致错误之前处理它们。
目前,当您跳转到它时,您的错误并没有被清除,并且因为它位于代码主体中,所以当您的第一组 More Code 完成并到达 Line3 标签时,它会被执行。
Sub Test1()
'Ignore the error.
'MsgBox won't appear, but code won't know an error occured.
'MsgBox says all's good anyway, even though the error is still present.
Dim Rng As Range
On Error GoTo SkipLineWithError
MsgBox Rng.Address
SkipLineWithError:
MsgBox "All good, error number is " & Err.Number
End Sub
更好的方法是在错误发生之前尝试捕获错误:
Sub Test2()
'Checks that Rng won't throw an error if referenced.
'Code has dealt with the error and says all's good.
Dim Rng As Range
If Not Rng Is Nothing Then
MsgBox Rng.Address
Else
MsgBox "Range not set"
End If
MsgBox "All good, error number is " & Err.Number
End Sub
虽然有时确实会发生错误,但需要妥善处理。为此,您跳出主程序,处理错误并再次跳回。
使用此代码注意 Exit Sub - Exit Sub 和 End Sub 之间的代码是您的错误处理所在。代码主体在到达Exit Sub 时结束。
Resume 告诉您的代码跳回哪里 - 它自己跳回导致错误的行,Resume Next 是后面的行错误,Resume <label> 跳转回您输入的标签,例如Resume Line3
Sub Test3()
Dim Rng As Range
On Error GoTo ErrorHandler
MsgBox Rng.Address
MsgBox "All good, error number is " & Err.Number
TidyExit:
'Close connections, general tidy up before ending procedure.
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 91 'Deal with the error if it happens.
'For this we'll give Rng a default address.
Set Rng = Sheet1.Range("A1")
Resume
Case Else
MsgBox "Error couldn't be handled... display an error message."
Resume TidyExit 'Jump to end of main body of code.
End Select
End Sub
编辑:根据@VBasic2008 的评论更新了代码。我的第一个代码很懒惰,错过了一个关键点。
我在这里几乎没有刮过表面,下面的链接应该会有所帮助。
on-error-statement
vba-error-handling