Ending a macro within a called subroutine

42k views Asked by At

I have a macro (CMOV) which calls another subroutine (CMOV2) that checks for a condition which, if met, displays a vbokaycancel message box which i set equal to a variable called irep,

I want it if someone hits cancel (irep=2) for it to call off the whole macro. That is not only exit CMOV2 but also exit CMOV.

Currently, I have

If jackal(1) <> vbNullString Then
    irep = MsgBox("Warning: You have a selection with two swingarms" _
          & " that are on the same radius and cannot swing past one another " _
          & Chr$(13) & " Choose Okay if you still wish to proceed otherwise " _
          & " choose Cancel to revise your order" & Chr$(13) & "         " _
          & jackal(1) & Chr$(13) & "      " & jackal(2), vbOKCancel)
    **If irep = 2 Then
    Exit Sub**
    Else: End If
    Else: End If
End Sub

at the end of the subroutine. The issue is that even though this exits the CMOV2, CMOV continues to run. Is there a way to end this sub, and the one which called it?

2

There are 2 answers

4
Cor_Blimey On BEST ANSWER
End

Note that End completely stops code execution (within the current call stack so it doesn't effect other projects like Addins etc (a good thing)) but it will close any open file handles (a good thing). On the other hand, , static and module level variables (if you use them) will lose their values and Class terminate methods won't be run so if you have more of an 'app' than a macro this may not be desired.

It sounds like for your purposes this is ok and is probably the simplest way to go about it.

A silly example:

Sub foo()
    Dim i As Long
    For i = 0 To 10
        If i = 2 Then
            Debug.Print "hooray"
            End
        Else
            Debug.Print "hip"
        End If
    Next i
End Sub
4
Siddharth Rout On

Declare a Boolean variable at the top and set it to True if the user presses cancel. Here is an example.

Dim ExitAll As Boolean

Sub CMOV()
    '
    '~~> Rest of the code
    '

    ExitAll = False

    CMOV2

    If ExitAll = True Then Exit Sub

    MsgBox "Hello World"

    '
    '~~> Rest of the code
    '
End Sub

Sub CMOV2()
    '
    '~~> Rest of the code
    '
    If jackal(1) <> vbNullString Then
        irep = MsgBox("Some Message", vbOKCancel)
        If irep = 2 Then
            ExitAll = True
            Exit Sub
        End If
    End If
    '
    '~~> Rest of the code
    '
End Sub