VBA:如何显示错误消息,就像标准错误消息一样,它具有“调试”按钮?
像往常一样,我使用 On Error Goto
语句创建一个错误处理程序,我放了几行清理代码并显示错误消息,但现在我不想失去默认处理程序的舒适性,这也指向了错误发生的确切行。如何做?
As usual, I create an error-handler using On Error Goto
statement, there I put a few lines of cleaning codes and display the error message, but now I don't want to lose the comfortableness of the default handler which also point me to the exact line where the error has occured. How can I do that?
提前感谢
首先是好消息。这段代码可以做你想要的(请注意行号)
First the good news. This code does what you want (please note the "line numbers")
Sub a()
10: On Error GoTo ErrorHandler
20: DivisionByZero = 1 / 0
30: Exit Sub
ErrorHandler:
41: If Err.Number <> 0 Then
42: Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
43: MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
44: End If
50: Resume Next
60: End Sub
运行时,会显示预期的MsgBox:
When it runs, the expected MsgBox is shown:
现在坏消息:
行号是旧版本的Basic的残留。编程环境通常负责插入和更新它们。在VBA和其他现代版本中,此功能将丢失。
And now the bad news:
Line numbers are a residue of old versions of Basic. The programming environment usually took charge of inserting and updating them. In VBA and other "modern" versions, this functionality is lost.
但是,在这里有几个自动添加行号的替代方法,可以节省您打字的繁琐工作,但是所有这些都似乎或多或少繁琐...或商业化。
However, Here there are several alternatives for "automatically" add line numbers, saving you the tedious task of typing them ... but all of them seem more or less cumbersome ... or commercial.
HTH!