Loop Structures

                                                                                                 << Back to Index
Loop structures allow you to execute one or more lines of code repetitively. The loop structures that Visual Basic supports include:
  • Do...Loop
  • For...Next
  • For Each...Next

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

The following code creates an integer array and entering values using for loop
 
Private Sub Form_Load ( ) 
 Dim arr(1 to 15) as  Integer
 Dim i As Integer, Limit As Integer
  Limit = InputBox ("Enter the no. of elements")
  For i = 1 to Limit
     arr(i)= InputBox("Enter a number")
   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,
Private Sub search_Click ()
   Dim found, num, arr(10)
   Dim i As Integer
   found = false
    For i = 1 to 10
     arr(i)= InputBox("Enter a number")
    Next i
     For Each num In arr
      found = True
   Next 
 Print "  item is found " 
 End Sub
Keep the following restrictions in mind when using For Each...Next:
  • For collections, element can only be a Variant variable, a generic Object variable, or an object listed in the Object Browser.
  • For arrays, element can only be a Variant variable.
  • You cannot use For Each...Next with an array of user-defined types because a Variant cannot contain a user-defined type.