For Each Command

Purpose

Repeats a group of statements for each element in a collection or hash.

Syntax

For Each element In group
[statements]
[Exit For]
[statements]
Next [element]

element:variable
group:collection or hash

Description

The For...Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. If there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example If…Then, and transfers control to the statement immediately following Next.

You can nest For...Each...Next loops by placing one For...Each...Next loop within another. However, each loop element must be unique.

Note   If you omit element in a Next statement, execution continues as if element is included. If a Next statement is encountered before its corresponding For statement, an error occurs.

Example

Dim Hi As Hash Int, i%

Hash Add Hi["David"], 3

Hash Add Hi["Paul"], 7

Hash Add Hi["Simon"], 5

For Each i In Hi[]

Print i, Each, Hi[$ Each]

Next

or

Local f As Form

AutoRedraw = True

OpenW 1 : OpenW 2 : OpenW 3

For Each f In Forms

Print "Form 1 Name: "; f.Name

Next

Do : Sleep : Until Win_3 Is Nothing

CloseW 2 : CloseW 1

Remarks

See Also

For Next, Hash

{Created by Sjouke Hamstra; Last updated: 06/10/2014 by James Gaite}