Also relevant to the discussion is the relatively unknown Erl
function. If you have numeric labels within your code procedure, e.g.,
Sub AAA()
On Error Goto ErrorHandler
1000:
' code
1100:
' more code
1200:
' even more code that causes an error
1300:
' yet more code
9999: ' end of main part of procedure
ErrorHandler:
If Err.Number <> 0 Then
Debug.Print "Error: " + CStr(Err.Number), Err.Descrption, _
"Last Successful Line: " + CStr(Erl)
End If
End Sub
The Erl
function returns the most recently encountered numberic line label. In the example above, if a run-time error occurs after label 1200:
but before 1300:
, the Erl
function will return 1200
, since that is most recenlty sucessfully encountered line label. I find it to be a good practice to put a line label immediately above your error handling block. I typcially use 9999
to indicate that the main part of the procuedure ran to its expected conculsion.
NOTES:
Line labels MUST be positive integers -- a label like MadeItHere:
isn't recogonized by Erl
.
Line labels are completely unrelated to the actual line numbers of a VBIDE CodeModule
. You can use any positive numbers you want, in any order you want. In the example above, there are only 25 or so lines of code, but the line label numbers begin at 1000
. There is no relationship between editor line numbers and line label numbers used with Erl
.
Line label numbers need not be in any particular order, although if they are not in ascending, top-down order, the efficacy and benefit of Erl
is greatly diminished, but Erl
will still report the correct number.
Line labels are specific to the procedure in which they appear. If procedure ProcA
calls procedure ProcB
and an error occurs in ProcB
that passes control back to ProcA
, Erl
(in ProcA
) will return the most recently encounterd line label number in ProcA
before it calls ProcB
. From within ProcA
, you cannot get the line label numbers that might appear in ProcB
.
Use care when putting line number labels within a loop. For example,
For X = 1 To 100
500:
' some code that causes an error
600:
Next X
If the code following line label 500
but before 600
causes an error, and that error arises on the 20th iteration of the loop, Erl
will return 500
, even though 600
has been encounterd successfully in the previous 19 interations of the loop.
Proper placement of line labels within the procedure is critical to using the Erl
function to get truly meaningful information.
There are any number of free utilies on the net that will insert numeric line label in a procedure automatically, so you have fine-grained error information while developing and debugging, and then remove those labels once code goes live.
If your code displays error information to the end user if an unexpected error occurs, providing the value from Erl
in that information can make finding and fixing the problem VASTLY simpler than if value of Erl
is not reported.