1

I have a quick question regarding Loops in Loops using Do Until. Will the first loop run the second loop if the criteria for the second one was fulfilled?

For Example:

Dim X
Dim Y
X = 0
Y = 0
' Loop 1
Do Until X = 20
   ' Loop 2
   Do Until Y = 5
   Y = Y + 1
   Loop
X = X + 1
Loop

So, loop 1 should loop 20 times and every time it loops it should run the second loop that loops 5 * 20 times. It doesn't seem to work. The second loop only seem to run 1 time and be ignored the rest of the time.

How to loop a loop in VBScript? Didn't help me to much.

5
  • 1
    You're missing the Y = 0 to reset the inner loop on each iteration of the outer loop. Commented Aug 30, 2016 at 16:00
  • Apparently How to loop a loop in VBScript? didn't help you much? I can only assume you didn't read it or follow it properly, that example is pretty comprehensive. Note the final comment on that answer "Without z = 0 the second loop won't be entered after the first turn." which is exactly the issue here except your variable is y = 0 not z = 0 but same applies. Commented Aug 30, 2016 at 16:07
  • Who close votes - "unclear what you're asking"? Really??, seems pretty clear to me! It is however a duplicate plain and simple. Commented Aug 30, 2016 at 16:21
  • 1
    @Lankymart probably someone in the close-vote review queue that's not very well versed in vbscript. I've seen it happen plenty of times before, not that it makes it right... Commented Aug 31, 2016 at 8:47
  • You can Search For Loop Or Do While Loop in the internet. Commented Aug 11, 2019 at 8:59

2 Answers 2

1

because the first time your inner loop runs, it exits when Y = 5 - as you do not change the value of Y again it will not run the next time because the condition has already been met.

Try this instead:

Dim X
Dim Y
X = 0
Y = 0
' Loop 1
Do Until X = 20
   ' Loop 2
   Do Until Y = 5
   Y = Y + 1
   Loop
   Y = 0 '// reset value of Y so that inner loop will run next time around
X = X + 1
Loop

or use a For...To... loop instead:

Dim X,Y

For X = 1 To 20
'// Do something...
    For Y = 1 To 5
    '// Do something 5 times
    Next
Next

This is because of the Y variables scope as you declared and assigned it's initial value outside of the loops.

You can read more about variable scope in VBScript in this MSDN article

Sign up to request clarification or add additional context in comments.

1 Comment

Good explanation. It's just personal preference but I always initialise / reset variables before the loop rather then after.
0

Y reaches 5 the first time the inner loop runs, so the next time round it already meets the until y = 5 condition so the loop never runs again.

Reset it before the loop or when the loop completes.

Y = 0
Do Until Y = 5

Comments