Quitting Sub from within an IF statement

  • Thread starter Thread starter stevem
  • Start date Start date
S

stevem

Ok, probably super simple question, but can't find the info.

I have a subroutine with one critical if statement at the top, I wan
to be able to quit out of the entire sub if this if statement is true
I tried just embedding end sub into the if statement but that didn'
work.

How is this done
 
Exit Sub will exit you out of a subroutine. If you are way deep in routines
calling routines, calling routines, you can do it several ways. One is to
set a global variable, say bOK that you set to false if you want to quit out
of each routine. Then have each calling routine check this variable to see
if it is true or false. If it false, they in turn issue an exit sub, etc.
The less pretty way is to just use an "End" statement (single word End on a
line). This stops everything. It also unloads all userforms, and all
values of any public variables.

Bob Flanagan
Macro Systems
http://www.add-ins.com
Productivity add-ins and downloadable books on VB macros for Excel
 
stevem,

if something = true then
exit sub'''>>>>not end sub
end if

HTH


Charle
 
Thanks for the help guys..

I posted the code and everything after the first post.

Exit sub works exactly how I wanted it to
 
I think you can also insert a label in your procedure with a "goto"
statement taking you to the "end sub" line. I have used this method, and it
will work if routine is a sub routine called by others, this way it won't
stop everything, it simply takes you to the end of that particular routine.
Check help file, line label must be at left margin, and must be followed by
a colon

SUB YourRoutine()

IF conditions met THEN
do stuff
ELSE
do other stuff
goto AnyLineLabel
END IF

More Code
More Code
More Code

AnyLineLabel:

END SUB
 
2 ways to structure your code



1st example uses exits sub comand if teststatement is false

2nd example runs your code if teststatement is true and ignores you
code if teststatement is false


sub test()
if something = false then
exit sub
end if
your code here
end sub



sub test1()
if something = true then
your code here
end if
end su
 

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

Back
Top