VBA 中有哪些好的错误处理模式?
特别是,在这种情况下我应该做什么:
... some code ...
... some code where an error might occur ...
... some code ...
... some other code where a different error might occur ...
... some other code ...
... some code that must always be run (like a finally block) ...
我想处理这两个错误,并在可能发生错误的代码之后恢复执行。另外,最后的finally 代码必须始终运行——无论之前抛出了什么异常。我怎样才能达到这个结果?
最佳答案
VBA 中的错误处理
出错时转到
ErrorHandlerLabel继续
(下一步
| ErrorHandlerLabel)On Error Goto 0
(禁用当前错误处理程序)Err
对象
Err
对象的属性通常在错误处理例程中重置为零或零长度字符串,但也可以使用 Err.Clear
显式完成.
错误处理例程中的错误正在终止。
范围 513-65535 可用于用户错误。
对于自定义类错误,您可以将 vbObjectError
添加到错误号中。
请参阅有关 Err.Raise
的 Microsoft 文档和 list of error numbers .
对于派生类中未实现的接口(interface)成员,您应该使用常量E_NOTIMPL = &H80004001
。
Option Explicit
Sub HandleError()
Dim a As Integer
On Error GoTo errMyErrorHandler
a = 7 / 0
On Error GoTo 0
Debug.Print "This line won't be executed."
DoCleanUp:
a = 0
Exit Sub
errMyErrorHandler:
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub
Sub RaiseAndHandleError()
On Error GoTo errMyErrorHandler
' The range 513-65535 is available for user errors.
' For class errors, you add vbObjectError to the error number.
Err.Raise vbObjectError + 513, "Module1::Test()", "My custom error."
On Error GoTo 0
Debug.Print "This line will be executed."
Exit Sub
errMyErrorHandler:
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Err.Clear
Resume Next
End Sub
Sub FailInErrorHandler()
Dim a As Integer
On Error GoTo errMyErrorHandler
a = 7 / 0
On Error GoTo 0
Debug.Print "This line won't be executed."
DoCleanUp:
a = 0
Exit Sub
errMyErrorHandler:
a = 7 / 0 ' <== Terminating error!
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub
Sub DontDoThis()
' Any error will go unnoticed!
On Error Resume Next
' Some complex code that fails here.
End Sub
Sub DoThisIfYouMust()
On Error Resume Next
' Some code that can fail but you don't care.
On Error GoTo 0
' More code here
End Sub
关于vba - VBA 错误处理有哪些好的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1038006/