I have a neat example I need help with. I am trying to find a way to handle my errors but keep my subfunctions modular(not needing to know about the rest of my code to work properly)
In Excel VBA, there's no Try/Catch functionality. There are native functions in VBA that return an error if they fail. I am looking to make the following example neat
Function wrapperForFunction(input As Variant) As Boolean
On Error goto returnTrue
fancyFunctionThatReturnsError(input As Variant)
wrapperForFunction = False
LINE OF CODE THAT SETS ERROR BACK TO WHAT IT WAS BEFORE CHANGING IT TO returnTrue
Return
returnTrue:
wrapperForFunction = True
LINE OF CODE THAT SETS ERROR BACK TO WHAT IT WAS BEFORE CHANGING IT TO returnTrue
End Function
Sub MainProgram()
On Error goto errorHandlerMain
'' do stuff
if wrapperForFunction(input) then 'do stuff
'' do morestuff
if wrapperForFunction(input) then 'do stuff
errorHandlerMain:
'non-erroring cleanup code
End Sub
Sub NestedSub()
On Error goto errorHandlerNestedSub
'' do stuff
if wrapperForFunction(input) then 'do stuff
errorHandlerNestedSub:
'non-erroring cleanup code
End Sub
What I am trying to avoid is this kind of solution
Function wrapperForFunction(input As Variant) As Boolean
On Error goto returnTrue
fancyFunctionThatReturnsError(input As Variant)
wrapperForFunction = False
Return
returnTrue:
wrapperForFunction = True
End Function
Sub MainProgram()
On Error goto errorHandlerMain
'' do stuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerMain ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
'' do morestuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerMain ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
errorHandlerMain:
'non-erroring cleanup code
End Sub
Sub NestedSub()
On Error goto errorHandlerNestedSub
'' do stuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerNestedSub ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
errorHandlerNestedSub:
'non-erroring cleanup code
End Sub
Any suggestions?? Is there a way to find out what the current "On Error goto x" state is and reset it back to what it was before you changed it? Like in
Function foobar()
Dim errorLine As Long: errorLine = CURRENT_ERROR_LINE
On Error goto 40
'do stuff
On Error goto errorLine
Return
40'cleanup code
End Function