Repeats a group of statements for each element in a collection.
Syntax:
For Each element [As datatype] In group
[statements]
[Exit For]
[statements]
Next [element]
The For Each...Next statement syntax has these parts:
Part |
Description |
|---|---|
Element |
Required in the For Each statement. Optional in the Next statement. Variable. Used to iterate through the elements of the collection. |
Datatype |
Required if element is not already declared. Data type of element. |
Group |
Required. Object variable. Refers to the collection over which the statements are to be repeated. |
Exit for |
Optional. Transfers control out of the For Each loop. |
Statements |
Zero or more statements between For Each and Next that run on each item in group. |
Next |
Required. Terminates the definition of the For Each loop. |
Remarks
Use a For Each...Next loop when you want to repeat a set of statements for each element of a collection or array.
A For...Next Statement works well when you can associate each iteration of a loop with a control variable and determine that variable's initial and final values. However, when you are dealing with a collection, the concept of initial and final values is not meaningful, and you do not necessarily know how many elements the collection has. In this case, a For Each...Next loop is a better choice.
Example:
Dim Data[3] as String
Data[1] = "One"
Data[2] = "Two"
Data[3] = "Three"
For Each I In Data
Print I
Next
Example:
Dim fso As Object
fso = CreateObject("Scripting.FileSystemObject")
Dim F As Object
F = fso.GetFolder("C:\")
For Each sf In f.SubFolders
Print sf.Name
Next