Keyword

For Each...Next


Description

Loops through the elements of a one-dimensional array or a class that implements the Iterable interface.

Usage

For Each element [As datatype] In array

[statements] [ Continue [For] ]

[ Exit [For] ]

Next [element]

Part

Type

Description

element

Same type as array

A variable of the same data type as array that refers to an element of array. The loop processes each value in array.

datatype

Any valid datatype

Optional: The data type of the array element.

array

Any valid datatype

A one-dimensional array whose data type must match datatype.

Statements

Statements to be executed repeatedly inside the loop.

Continue

If a Continue statement is present, execution skips directly to the loop's Next statement, thereby causing another loop iteration unless the end is reached.

Exit

If an Exit statement is present, execution skips over the remaining statements in the loop and resumes with the statement following the Next statement. See the Exit statement for additional options that are relevant for nested loops.

Notes

For...Each loops through the values in the array in index order.

As with other block statements, variables declared within a For...Each loop go out of scope when the loop finishes or exits.

Sample code

Iterate through an array:

Var days() As String = Array("One", "Two", "Three", "Four", "Five")
Var output As String
For Each d As String In days
  output = output + d
Next

Calculate the sum of values in an array:

Var values() As Double = Array(1.5, 5.5, 8.0, 45.0, 22.5)
Var sum As Double
For Each d As Double In values
  sum = sum + d
Next
// sum = 82.5

Compatibility

All project types on all supported operating systems.

See also

For...Next, Var statements; Array keyword