Obtain Name of Function or Sub

  • Thread starter Thread starter Roger Smith
  • Start date Start date
R

Roger Smith

Hi Experts

I would like to include the name of the current function or subroutine in my
error handler output. Is there any property that will provide the name or
context of the current point in the call chain?

Thanks much,

Roger
 
I create a string variable that stores the name of the subprocedure, location
or any other desired data that I want displayed in the event of an error that
may occur during the running of a subprocedure. Then my On Error procedure
uses a MsgBox that returns the data stored in the variable.

For example:

Sub TryThis()

Dim strErrLocation as string

On Error Goto Err_Handler

strErrLocation = "Start of Subprocedure ABC."

.... other code

strErrLocation = "Allocating Costs portion of the subprocedure."

.... other code

strErrLocation = "Final Clean-Up stage of subprocedure."

.... final clean-up code

Exit Sub

Err_Handler:
MsgBox strErrLocation & vbCrLf & vbCrLf & _
"Err Number: " & Err.Number & " Err Description: " & Err.Description

End Sub

I hope this helps. Good Luck.
 
Thanks Pard

That works so long as the code stays within the context of the current Sub.
But, if you leave the current Sub, say for example with a function call,
then you lose the sErrLocation variable because while you are within the
function call the code is operating in a different context. I was looking
for a way to fetch the name of the function or sub out of one of the
properties - if that information exists.

Cheers,

Rj
 
I don't think what you want is possible.
The answer is to do a On Error Goto 0 before execution
moves to the other Sub or Function and then add an
error handler for that other procedure. Then when you come back
in your orginal procedure do another On Error Goto Err_Handler.

RBS
 
Just for ideas -

Sub test()
Dim v
On Error GoTo errH
v = "a" ' mismatch
' v = 1 ' div by zero
test2 v
Exit Sub
errH:
MsgBox Err.Description
End Sub

Sub test2(v)
On Error GoTo errH
10
20
30 test3 v
40
Exit Sub
errH:
s = "test2, line:" & Erl & vbCr & Err.Description
Err.Raise 12345, , s
End Sub

Sub test3(v)
On Error GoTo errH
10
20
30 v = v / 0
40
Exit Sub
errH:
s = "test3, line:" & Erl & vbCr & Err.Description
Err.Raise 12345, , s
End Sub

Regards,
Peter T
 
If that's the only concern, declare the variable Public, then it is available
from any subprocedure or function in the program.
 
Thanks Peter - that helps... you gave me some new ideas. Much appreciated

Roger
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top