VBA:显示标准的运行时error handling程序

我有一个正确的方法来处理Excel中的VBA中的错误的问题。 如果发生特定的错误,例如xxxxxxx,则应显示一个MsgBox。 如果发生另一个错误,则会popup标准的运行时error handling程序。 这怎么能做到呢? 以下是示例代码:

On Error Resume Next 'Line of code that causes an error here. If Err.Number = xxxxxxx Then MsgBox "Specific error message." ElseIf Err.Number = 0 Then Do nothing Else 'Some error other than xxxxxxx. 'This is the problem. Here I would like to display standard run-time error 'handler without causing the error again. End If On Error GoTo 0 

你可以通过把它放到你的“Else”块来得到一个非常类似于标准错误信息的消息框:

 MsgBox "Run-time error '" & Err.Number & "':" & _ vbNewLine & vbNewLine & _ Error(Err.Number), vbExclamation + vbOKOnly, _ "YourProjectNameHere" 

但这只是一个传真。 这不是VB6提供的实际的错误消息对话框; 它只是格式化看起来像。 error handling现在仍然由“On Error Resume Next”语句禁用。

但是如果你确实想要调用标准的error handling代码,你可以把它放在“Else”块中:

 Dim SaveError As Long SaveError = Err.Number On Error Goto 0 Error (SaveError) 

此代码保存错误号,重新启用error handling,然后重新提出错误。 你这样调用VB运行库的真正的error handling机器。 但是要小心:如果这个错误没有被调用链中某个更高的活动error handling程序所捕获,那么在用户点击“OK”button后,它将终止你的程序

请注意,您还将失去在error handling程序中使用“Erl”发生错误的实际行号的能力,因为您正在使用“Error(SaveError)”语句重新生成运行时错误。 但是这可能并不重要,因为大多数VB代码实际上并不使用任何行号,所以Erl只是返回0。

replace错误继续下一步

 On Error Goto SomePlaceInCodeToHandleErrors SomePlaceInCodeToHandleErrors: If Err.Number = XXXX Then MSGBOX "Message" End If 

看看这个堆栈溢出线程的一些更多的信息和示例代码。

在您的VBA选项中,select“中断未处理的错误”。
要启用处理使用on error goto SomeLabelon error resume next
停止error handling使用on error goto 0

你的问题在这方面是矛盾的。 如果启用error handling,那么您将禁用标准error handling。

正如DaMartyr所说,你仍然可以使用msgbox err.description

所以为了跟进JeffK的新build议,下面的代码似乎可以在VBA下正常工作,而且我也看不到使用它的危险。 终止Excel是很重要的,因为这可能会失去很多工作,但是由于代码总是检查错误是否在那里?

谢谢JeffK这个有趣的想法。

 Dim savedNumber As Long 
On Error Resume Next
'Line of code that causes an error.
If Err.Number = XXXXXXX Then
'Specific error message.
ElseIf Err.Number <> 0 Then
savedNumber = Err.Number
On Error GoTo 0
Error savedNumber
End If
Err.Clear
On Error GoTo 0