How to return from a function in case of error in VBA How to return from a function in case of error in VBA vba vba

How to return from a function in case of error in VBA


You need to put EXIT FUNCTION there to get out of further execution:

Function GetEditboxValue(control As IRibbonControl, text As String) As String    If Not IsMissing(text) Then        If Not IsNumeric(text) Then            MsgBox "Please enter numeric value only."            EXIT FUNCTION        End If    End If    If control.id = "xyz" Then    spaceAboveTable = text    End IfEnd Function


In a generalized sense (I'm not actually saying anything that hasn't already been said):

Function Foo(inputVar As Double) As Double    On Error GoTo ErrorHandler    ' Code assigning something to returnValue and defaultOutput    Foo = returnValue    Exit Function    ErrorHandler:    Foo = defaultOutput End Function

No reason it has to be Double, of course.

(Edited because I had a second "Exit Function" instead of "End Function.")


You can use Exit Function after your MsgBox statement