Handle Error in Called Sub

G

Guest

Trying to perfect this a little more...

I've got this code that measures the length (in minutes) of a procedure.

Sub TimeLoop(strFncToCall As String)
On Error GoTo TimeLoop_Err
Dim sngStart As Single
Dim sngEnd As Single
Dim lngLoop As Long
Dim Msg As String
Dim Ans As Integer

sngStart = Timer
Application.Run strFncToCall
sngEnd = Timer

'Creates a message box
Msg = "Process completed successfully!"
Msg = Msg & vbNewLine & vbNewLine
Msg = Msg & "Process Time: " & Format$((sngEnd - sngStart) / 60, "0.0")
& " minutes"
Ans = MsgBox(Msg, vbInformation, "Refresh Status")

TimeLoop_Exit:
DoCmd.SetWarnings True
Exit Function

TimeLoop_Err:
MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error - Time
Loop"
Resume TimeLoop_Exit

End Sub

If I encounter an error in the "called" procedure - that error is reported,
and then the code continues to the MsgBox in TimeLoop. Ideally, if there is
an error in the called procedure, it should report the error and stop. How
do I accomplish this?
 
D

Douglas J. Steele

Sounds as though strFncToCall is raising the error, handling it, then using
Resume to clear the error, so that TImeLoop knows nothing about it.

You can either remove the Resume statement from strFncToCall, or you could
have strFncToCall raise another error for TImeLoop to capture.
 
G

Guest

You are correct, strFnctoCall is raising the error and reporting it via the
statements below. So how do I make TimeLoop aware of the error so it can
"bail out" and not continue on to the MsgBox "process completed
successfully"?

MassImport_Exit:
DoCmd.SetWarnings True
Exit Function

MassImport_Err:
MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error
Notification"
Resume MassImport_Exit
 
D

Douglas J. Steele

Does MassImport return anything? If not, have it return True if successful,
and False if not, and then trap that value in the calling routine.

Otherwise, you could change

MassImport_Err:
MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error
Notification"
Resume MassImport_Exit

to something like:

MassImport_Err:
MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error
Notification"
Err.Raise -1
Resume MassImport_Exit

and then change your error handler in the calling routine to check for
Err.Number = -1 and take a different action than for a "legitimate" error.
 

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

Top