Loop Structures

See Also

Loop structures allow you to execute one or more lines of code repetitively. The loop structures that Visual Basic supports include:

Do...Loop

Use a Do loop to execute a block of statements an indefinite number of times. There are several variations of the Do...Loop statement, but each evaluates a numeric condition to determine whether to continue execution. As with If...Then, the condition must be a value or expression that evaluates to False (zero) or to True (nonzero).

In the following Do...Loop, the statements execute as long as the condition is True:

Do While condition
statements

Loop

When Visual Basic executes this Do loop, it first tests condition. If condition is False (zero), it skips past all the statements. If it's True (nonzero), Visual Basic executes the statements and then goes back to the Do While statement and tests the condition again.

Consequently, the loop can execute any number of times, as long as condition is nonzero or True. The statements never execute if condition is initially False. For example, this procedure counts the occurrences of a target string within another string by looping as long as the target string is found:

Function CountStrings (longstring, target)
   Dim position, count
   position = 1
   Do While InStr(position, longstring, target)
      position = InStr(position, longstring, target)_
       + 1
      count = count + 1
   Loop
   CountStrings = count
End Function

If the target string doesn't occur in the other string, then InStr returns 0, and the loop doesn't execute.

Another variation of the Do...Loop statement executes the statements first and then tests condition after each execution. This variation guarantees at least one execution of statements:

Do
statements

Loop While condition

Two other variations are analogous to the previous two, except that they loop as long as condition is False rather than True.

Loop zero or more times Loop at least once
Do Until condition
  statements
Loop
Do
  statements
Loop Until condition

For...Next

Do loops work well when you don't know how many times you need to execute the statements in the loop. When you know you must execute the statements a specific number of times, however, a For…Next loop is a better choice. Unlike a Do loop, a For loop uses a variable called a counter that increases or decreases in value during each repetition of the loop. The syntax is:

For counter = start To end [Step increment]
statements

Next [counter]

The arguments counter, start, end, and increment are all numeric.

Note   The increment argument can be either positive or negative. If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If increment is negative, start must be greater than or equal to end for the body of the loop to execute. If Step isn't set, then increment defaults to 1.

In executing the For loop, Visual Basic:

  1. Sets counter equal to start.

  2. Tests to see if counter is greater than end. If so, Visual Basic exits the loop.

    (If increment is negative, Visual Basic tests to see if counter is less than end.)

  3. Executes the statements.

  4. Increments counter by 1 or by increment, if it's specified.

  5. Repeats steps 2 through 4.

This code prints the names of all the available Screen fonts:

Private Sub Form_Click ()
   Dim I As Integer
   For i = 0 To Screen.FontCount
      Print Screen.Fonts(i)
   Next
End Sub

In the VCR sample application, the HighlightButton procedure uses a For...Next loop to step through the controls collection of the VCR form and show the appropriate Shape control:

Sub HighlightButton(MyControl As Variant)
   Dim i As Integer
   For i = 0 To frmVCR.Controls.Count - 1
      If TypeOf frmVCR.Controls(i) Is Shape Then
         If frmVCR.Controls(i).Name = MyControl Then
            frmVCR.Controls(i).Visible = True
         Else
            frmVCR.Controls(i).Visible = False
         End If
      End If
   Next
End Sub

For Each...Next

A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for each element in a collection of objects or in an array instead of repeating the statements a specified number of times. This is especially helpful if you don't know how many elements are in a collection.

Here is the syntax for the For Each...Next loop:

For Each element In group
statements

Next element

For example, the following Sub procedure opens Biblio.mdb and adds the name of each table to a list box.

Sub ListTableDefs()
   Dim objDb As Database
   Dim MyTableDef as TableDef
   Set objDb = OpenDatabase("c:\vb\biblio.mdb", _
   True, False)
   For Each MyTableDef In objDb.TableDefs()
      List1.AddItem MyTableDef.Name
   Next MyTableDef
End Sub

Keep the following restrictions in mind when using For Each...Next: