For Each...Next Statement

A For Each...Next statement iterates through the elements supplied in a list.

A For Each statement specifies the following:

The following syntax applies to For Each...Next statements.

For Each <LoopControlVariable> In <expression>
   [statements]
Next [expression]

An identifier specifies the loop control variable. The enumerator expression must evaluate to a list or an enumerator function (see TreeIterator below). The loop control variable must be of a type that is compatible with the items in the list. Nested For Each...Next statements must each use their own loop control variable.

The enumerator expression is evaluated before the loop begins. At the beginning of each iteration, the next element in the list is assigned to the loop control variable. If all the elements in the list have been evaluated, the loop terminates; otherwise the statement block is executed.

The example below shows a typical For Each...Next loop.

Rule total As Integer
   Dim counter As Integer = 0
   Dim numList As list = {0, 2, 4, 6, 8, 10}  

   For Each counter in numList
      total = total + counter
      printValue("Total = " + stringValue(total) + _
         " Counter = " + stringValue(counter))
   Next
End Rule
Output:
"Total = 0 Counter = 0"
"Total = 2 Counter = 2"
"Total = 6 Counter = 4"
"Total = 12 Counter = 6"
"Total = 20 Counter = 8"
"Total = 30 Counter = 10"

You can exit a For Each...Next loop by using an Exit For statement in the body of the loop.

Note: See Exit Statement for more information.