views:

69

answers:

1

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?

Thanks in advance.

+2  A: 

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

When it runs, the expected MsgBox is shown:

alt text

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!

belisarius
Charles Williams
@Charles yep. That is one of the references in the page I cited. Tnx!
belisarius
@belisarius, thanks so much for the code, precious info, and useful external references. Just curious, is there a way to bring the line to reader's focus, even highlight them and enter debugging mode? Is that really internal functionality?
Vantomex
@Vantomex Glad to help. I don't know if there is a way to do that. Perhaps you may look at VBIDE.dll ... but I'm NOT sure. Good luck!
belisarius
@Vantomex, you could also look at the help for 'Application.Goto', which you can use to at least jump to the right procedure in the IDE.
jtolle
Actually, 'Application.Goto' could also be used with 'Application.Caller' to better answer your last question: http://stackoverflow.com/questions/3861431/vba-how-to-get-the-last-used-cell-by-vba-code-when-the-last-error-occured-in-a-w
jtolle
@jtolle, Thank you very much.
Vantomex
@jtolle, I successfully made the cursor jump to a procedure name using `Application.Goto`, however what actually I want is to make the cursor goto the line (in VBE) where the error last occured. I think I will ask a new question about this one.
Vantomex