variable number of For Next loops

K

KAH

Is there any way I can have a variable number of nested For ... Next loops?
In other words, I want x loops. If x=2 there would be 2 loops, if x=3, 3
loops.

This is a follow-up to a question I posted May 29 about all permutations.
The answer I got was helpful and gave me ideas but didn't actually solve my
problem. I realize what I really need to figure out is the variable number of
loops.

Thanks for any help.
 
P

Patrick Molloy

you need to read up on RECURSION
it sounds like what you really need is a recursive function ... ie one that
calls itself.
an example would be when finding all the files in a folder ... the function
created to find files would call itself if for any subfolders.
Another example would be for factorial numbers eg 5! is the same as 5x4!
which is 5x5x3! ...
 
R

Rick Rothstein

You can't create nested loops "on the fly", but maybe a solution like this
would work for you. Set up all the nested loops you will possibly need and
check whether that level should be run or not in its first statement and, if
not, exit the loop before it does anything (this will short circuit and
further nested loops right then and there). Here is an example structure for
you to consider (I set it up for 4 nested loops, but the concept can be
carried on as needed)...

NumberOfLoops = 2
For A = # To #
'
' Code for the "A" loop
'
For B = # To #
If NumberOfLoops = 1 Then Exit For
'
' Code for the "B" loop
'
For C = # To #
If NumberOfLoops = 2 Then Exit For
'
' Code for the "C" loop
'
For D = # To #
If NumberOfLoops = 3 Then Exit For
'
' Code for the "D" loop
'
Next
Next
Next
Next
 
K

KAH

Thanks to everyone for their rapid responses. This idea of exiting loops
works best for my program and is simple. Thanks!
 

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