7. VbScript | Do Loop

Try running the codes yourself for practice.

The ‘Do Loop’

Today we are going to talk about Do Loops in VbScript; which loops or repeats something until a condition is satisfied.

For example:

Output:

Here the message box will continue to run a Message Box after you close the Message Box.

6 then 6 then the same and so on without stop….

The only way to close the message box is by ending the task on Task Manager; specifically the program wscript.exe.

7

Exiting Loop

To exit the Loop, you use exit do:

Output:

The script exits the loop the first time it runs. So once you close the message box, the VbScript exits the loop and continues the script after the loop.

Differently, you can use wscript.quit:

Output:

When you use wscript.quit, you are not only quitting the loop, but you are quitting the VbScript itself.


So if you have something after the Do Loop, wscript.quit does not allow the VbScript to run it; but forces the VbScript to quit. ie:

Output:

only

6

But if you use exit do, then the script continues:

Output:

6 and then 8

Exiting Loop by Condition

Example 1:: So set a condition to break the loop:

Or

Output:

55


Example2:: Another example of breaking Do Loop by condition:

*For the Loop to break, a has to be greater than 4.

Output:

55


Example3::

Output:

a=0 → 0+1=1 → a=1 → 1+1=2 → a=2 →… a=7 → Break Loop


Example4::

Or

Output:

56

*Notice that

and

are the exact same command.


Example5:: Using If Then Statements to set up Break Loop Condition:

Output: So the VbScript only exits the loop if the pass = wired. Otherwise, the VbScript loops back.

A more extensive version of Example5::

Output:

57


What's Your Opinion?