Avatar of deskchains
Flag for United States of America asked on

Conditionally exit a subroutine

I have a button in my excel workbook that launches nine macros/routines.  The macros run one after the other and are dependent on the data generated by one or more of the previous.  Of course when I started i only ran three or so macros and the whole thing crept/grew to where I am now.  Problem I have is that I want to exit out of the routines if a error condition is found (I have a variable, error count, and if this equalls one or more the condition is met).  So say following the execution of macro #3 I run my error check and If if finds an error it will bail on the remaining macros.  

Alternately i can embed my macro into macro #3 and do the same bailing out.  

Still another option is to merge all the macros  into one , embed the error check code, and bail out if an error is found.  Bottom line is I don't know how to do this, nor how best to do this.
Visual Basic ClassicMicrosoft Excel

Avatar of undefined
Last Comment
Martin Liss

8/22/2022 - Mon
Phillip Burton

To exit a subroutine, use Exit Sub

To do that conditionally, test for the condition using IF THEN, then have Exit Sub as the THEN part.

If you want to chain them, then create a new routine that will invoke the other nine in succession.  After each routine ends, you check to see if they raised an error and act appropriately.
Martin Liss

View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.

I used a similar approach, but made the bError variable a global so that I could reference it multiple times for the same test.  not sure if i needed to, but that is what i did.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Martin Liss

I'm glad I was able to help.

In my profile you'll find links to some articles I've written that may interest you.
Marty - MVP 2009 to 2014