Loops


Operators are used to repeat the sequence of commands.

There are several loop operators in VBScript:

1.Do ... Loop

This operator is running a group of commands until a specified condition is true or until when it becomes true. Checking the condition can be implemented in the loop heading:

 Do [{While | Until} condition]

    [statements]

    [Exit Do]

    [statements]

 Loop 

or at the end of loop:

 Do

  [statements]

  [Exit Do]

  [statements]

 Loop [{While | Until} condition]

For example:

 Dim Resp, Num

 Loop

   Num = Int(6 * Rnd + 1)

   Resp = Application.MessageBox Num & " More?", "",_

     vbYesNo or vbQuestion

 Do Until Resp = vbNo

 

2. While..Wend

It is a condensed version of the operator Do .. Allows a execution of group of commands until condition is true.

Syntax:

 While condition

   [statements]

 Wend

 

3.  For..Next

This loop repeats a group of commands a specified number of times.

 For counter = start To end [Step step]

   [statements]

   [Exit For]

   [statements]

 Next

For example, this loop initializes the three-dimensional array:

 Dim A(9, 9, 9)

 Dim I, J, K

 For I = 0 To 9

   For J = 0 To 9

     For K = 0 To 9

       A(I, J, K) = 1

     Next

   Next

 Next

 

4. For Each..Next

The operator loop For Each .. Next repeats a group of commands for each element of the array or collection:

 For Each element In group

   [statements]

   [Exit For]

   [statements]

 Next

For example, the following code displays a list of files in the root directory of drive C:\

  Dim fso, f, f1, fc, s

  Set fso = CreateObject("Scripting.FileSystemObject")

  Set f = fso.GetFolder("c:\")

  Set fc = f.Files

  For Each f1 in fc

     s = s & f1.name & vbNewLine

  Next

  Application.MessageBox s, "Files in c:\", vbOkOnly