Name
For Each . . . Next Statement
Syntax
For Eachelement
Ingroup
[statements
] [Exit For] [statements
] Next
-
element
Use: Required
Datatype: Variant
A variant to which the current element from the group is assigned.
-
group
Use: Required
A collection or an array.
-
statements
Use: Optional
A line or lines of program code to execute within the loop.
Description
Loops through the items of a collection or the elements of an array.
Rules at a Glance
The
For...Each
code block is executed only ifgroup
contains at least one element.All
statements
are executed for eachelement
ingroup
in turn until either there are no more elements ingroup
, or the loop is exited prematurely using theExit
For
statement. Program execution then continues with the line of code followingNext
.For
Each...Next
loops can be nested, but eachelement
must be unique. For example:For Each myObj In AnObject For Each subObject In myObj SName = subObject.NameProperty Next Next
uses a nested
For
Each...Next
loop, but two different variables,myObj
andsubObject
, representelement
.Any number of
Exit
For
statements can be placed with theFor
Each...Next
loop to allow for conditional exit of the loop prematurely. On exiting the loop, execution of the program continues with the line immediately following theNext
statement. For example, the following loop terminates once the program finds a name in themyObj
collection that has fewer than 10 characters:For Each subObject In myObj SName = subObject.NameProperty If Len(Sname) < 10 then ...
Get VBScript in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.