1

I have a sub "main" which calls sub "prepare" as well as other subroutines. I have an if statement in "prepare" that exits the sub if a condition is met. However, it only exits that specific subroutine and then goes on to execute all of the other subroutines in "main".

    If oAltIDLocationDictionary.Exists(sAltID) Then
        MsgBox "It appears that there are two duplicate ID's in your alternate ID list.  Duplicate ID's cannot be processed, please consolidate the location information into a single ID or remove the duplicate ID from the Alt-ID list."
        Exit Sub
    End If

Is there a way to exit the "main" from the "prepare" sub it's calling so that when the condition is met in the "prepare" sub the "main" sub stops and no further code is executed?

9
  • You could use End. Commented Jan 14, 2018 at 19:44
  • That worked! It didn't work a minute ago, I was getting an error that the if statement wasn't ended properly, but it worked just now. Commented Jan 14, 2018 at 19:46
  • Thanks! If you put that as an answer I will mark it as the accepted answer. Commented Jan 14, 2018 at 19:46
  • 1
    I'd just like to take the opportunity to highlight the use of functions. If your Sub was a function, you could get it to return a specific value on exiting - then the rest of the code in Main or whatever can behave differently. It's a good concept to get hold of and it seems you're at a stage where it may be learned and come in handy one day... Commented Jan 14, 2018 at 20:09
  • 2
    @jamheadart agreed. End is essentially a Big Red Button that nukes the entire runtime context (i.e. resets any global state back to defaults). I've never needed to use End even once - the proper answer is proper control flow, not a Big Red Button. Commented Jan 14, 2018 at 20:54

2 Answers 2

3

To cease execution of your macro immediately, without returning to the calling procedure, you can use the End statement.

Sign up to request clarification or add additional context in comments.

1 Comment

As @mats-mug pointed out in his comment on the original question, using End is like a big red button that nukes everything, and clears any state that your code has developed..
1

You can convert the subs into functions, and if the functions return a certain value, the main sub will then exit.

Sub Main()
    Dim bTest As Boolean

    ' blah blah

    bTest = Prepare
    If bTest Then Exit Sub

    ' blah blah

End Sub

Function Prepare() As Boolean

    Prepare = False

    If oAltIDLocationDictionary.Exists(sAltID) Then
        MsgBox "It appears that there are two duplicate ID's in your alternate ID list."
        Prepare = True
        Exit Function
    End If

End Function

Comments

Your Answer

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