0

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)?

3
  • userNum() knows nothing about the callee foo(), 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 use End instead of Exit Sub. Commented Jul 9, 2019 at 9:03
  • @omegastripes does using End by itself that work? I've searched the VBA dpcumentation and I can't find any mention of End without another keyword immediately after it. Source: learn.microsoft.com/en-us/dotnet/visual-basic/… Commented Jul 9, 2019 at 13:46
  • End just terminates code execution. Like you press "stop" button in debugger. Commented Jul 9, 2019 at 19:09

1 Answer 1

1
  1. Declare variables.
  2. I would recommend using Application.InputBox with Type:=1 to accept numbers as input.
  3. Declare the result as Variant so that you can handle the the Cancel button in the InputBox. Also use that to decide whether you want to show the number or not.

Is this what you are tying? (Untested)

Option Explicit

Sub foo()
    Dim numb As Variant
    numb = userNum()

    If numb <> False Then MsgBox numb
End Sub

Function userNum() As Variant
    Dim Ret As Variant

    Ret = Application.InputBox(Prompt:="Enter you number", Type:=1)

    If Ret = False Then
        userNum = False
        Exit Function
    ElseIf Ret < 0 Then
        MsgBox ("Invalid: your number must be positive.")
        userNum = False
        Exit Function
    End If

    userNum = Ret
End Function
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a more succint way of doing it that doesn't involve having the If numb <> False Then ... lines in the sub? Similar to what I have in my question.
If numb <> False handles both the situation when the user presses cancel as well as any negative numbers. If you wanted number greater than 0 then it would have been a much simpler solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.