'How can I call a subroutine after an error?

I'm working on user-proofing a VBA app in Excel and I realized I'm constantly rewriting a lot of the same code to create specific error messages that are fed strings of info for the user to be able to tell me when they inevitably call me to say they're getting errors.

I want to create something like this to simply call on each error and pass the particulars:

Sub GenericError(ErrNum As Long, ErrDesc As String, sequence As String, errtype As String)
'In case of error, returns actual error code and calls for abort; if no abort then can debug
Dim msgstrng As String
msgstring = sequence & " error " & errtype _
    & vbLrCf & "Error code " & ErrNum & " - " & ErrDesc
MsgBox msgstring, , sequence & " Error!"
cont = Abort_Check()
On Error GoTo 0
End Sub

Then ideally I could use something like

On Error Call GenericError(Err.Number, Err.Description, "Startup Sequence", "File Not Found")
'code that opens a file....
On Error goto 0

It seems like On Error only works with goto or resume; there are a bunch of modules that would need this in a lot of subs so writing basically this in a bunch of different GoTo blocks is annoying. Is there a solution for me to use an error to call a sub like this?



Solution 1:[1]

Encapsulate your error generators in a try function

Public Function TryDoThisThing( byval ipInput1 as variant, byval input2 as variant,byref opReturnValue as variant, byref opErrorNumber as long, byref opErrorDescription as String) as boolean

   On Error Resume Next
   opReturnValue = DoThistThing(ipInput1, ipInput2)
   TryDoThisThing = err.number = 0
   opErrorNumber = err.number
   opErrorDewscription = Err.description
   Err.Clear

Exit Function

Then in your code you'd have

If not TryDoThisThing(val1, val2, myResult, myErrNo,myErrDesc) then

    GenericError myErrNo, myErrDesc, sequence , errtype
    <any other corrective actions>
end if

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1