How do I get a VBA sub to exit from within a called function if an error occurs?
I've tried placing Exit Sub statements within the relevant functions, but whenever I save and re-open the file, VBA automatically changes it to Exit Function.
For example, how do I get the code below
Sub foo()
userNum = userNum()
MsgBox(var)
End Sub
Function userNum() As Integer
userNum = InputBox("Enter your positive number")
If var < 0 Then
MsgBox("Invalid: your number must be positive.")
Exit Sub
End If
End Function
to not execute MsgBox(var)?
userNum()knows nothing about the calleefoo(), so generally the only way to control the flow is to return some value and build a conditional statement within the sub. In this partucular case you may just useEndinstead ofExit Sub.Endby itself that work? I've searched the VBA dpcumentation and I can't find any mention ofEndwithout another keyword immediately after it. Source: learn.microsoft.com/en-us/dotnet/visual-basic/…Endjust terminates code execution. Like you press "stop" button in debugger.