Exit Sub from Main Sub

L

Len

Hi,

I try to find ways on how to set vba code that when anyone or more
than one of subroutines has prompted "Exit Sub" will exit the main sub
program

E.g

Sub main()
.....
.....
.....
Call abc
End Sub

Sub abc()
.....
.....
Exit Sub
.......
End Sub

Sub def()
.....
.....
Exit Sub
.......
End Sub

Any helps will be appreciated and thanks in advance

Regards
Len
 
B

Bob Phillips

Here is one way raising an error

Sub main()

On Error GoTo Exit_Main

Call abc

Exit_Main:
'add any tear-down code
Exit Sub

Exit_Error:
If Err.Number = 99999 Then Resume Exit_Main
MsgBox Err.Description
Resume Exit_Main
End Sub

Sub abc()

'do more stuff
If Time >= TimeValue("12:00:00") Then Err.Raise 9999

MsgBox "Earlier than 12"

Call def

End Sub

Sub def()

'do stuff

If Time >= TimeValue("11:00:00") Then Err.Raise 9999

MsgBox "Earlier than 11"

End Sub
 
R

Ryan H

I like to use a variable named StopCode. Before your main sub starts, by
default it is False, but set it to True just before you exit the sub or
whenever you like. You can declare the variable at the top of the module if
all of these subs are in one module. If they are in multiple modules you
will have to declare StopCode as a Public variable. Hope this helps! If so,
click "YES" below.

For example,

Dim StopCode As Boolean

Sub main()
......
......
......
Call abc
If StopCode = True Then Exit Sub
......
......
Call def
If StopCode = True Then Exit Sub
......
......
End Sub

Sub abc()
......
......
StopCode = True
Exit Sub
........
End Sub

Sub def()
......
......
StopCode = True
Exit Sub
........
End Sub
 
A

AB

Just put 'End' before 'Exit Sub'.

If all you want is to stop the main procedure from running when a
specific condition is met and the 'Exit Sub' happens, then you can
just put 'End' before every 'Exit Sub' and it will terminate all
running subs.
e.g.:

Sub Main()
Call abc
Call def
End Sub

Sub abc()
...
End ' <- this 'End' stops every currently running sub (including
Main)
Exit sub
End sub

Sub def()
...
End ' <- this 'End' stops every currently running sub (including
Main)
Exit sub
End sub
 
R

Ryan H

I don't know if I would recommend using End. Because using End will clear
any Public variables values, or close any userforms that he may want to
remain open. I would recommend using End if you want "absolutely everything"
to stop.
 
L

Len

Hi All,

Sorry for delay in replying my post as I was away in the weekend
Thanks for your great helps and your suggestions

I will try it out

Regards
Len
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top