Question how to stop a recursion procedure

andrews

Well-known member
Joined
Nov 22, 2011
Messages
167
Programming Experience
5-10
I have a recursion sub but when some condition is true during the loop I want to leave the procedure with Exit Sub but it will not do it.
Any idea?
 
Hi,

You have to remember what Recursion does. Recursion is a routine which "Calls Itself" so when you say Exit Sub all you are doing is Exiting the Current iteration of the recursion. The way to get round this is to create a Class Level Boolean variable or a Static Boolean variable in the routine, called bolCancel, which can then be tested for within the routine. If you then set this variable to True then all iterations of the routine will fire the Exit Sub statement until the recursion has been exited.

Hope that helps.

Cheers,

Ian
 
Last edited:
Exit Sub is fine as long as you return a result from doing whatever it is you are doing. If you make your Sub a Function instead, and return a Boolean, you no longer need a global.
 
When you program a recursive procedure, it's like winding up a string on a yoyo. You can't simply end the recursion when it's deep inside. You need to unwind the string from the yoyo, one by one until you're back where you started.
 
Back
Top