Name
For Each . . . Next Statement
Syntax
For EachelementIngroup[statements] [Exit For] [statements] Next
elementUse: Required
Data Type: Variant
A variable to which the current element from the group is assigned.
groupUse: Required
A collection or an array.
statementsUse: 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...Eachcode block is executed only ifgroupcontains at least one element.All
statementsare executed for eachelementingroupin turn until either there are no more elements ingroup, or the loop is exited prematurely using theExitForstatement. Program execution then continues with the line of code followingNext.ForEach...Nextloops can be nested, but eachelementmust be unique. For example:For Each myObj In anObject For Each subObject In myObject sName(ctr) = subObject.NameProperty ctr = ctr + 1 Next Nextuses a nested
ForEach...Nextloop, but two different variables,myObjandsubObject, representelement.Any number of
ExitForstatements can be placed with theForEach...Nextloop to allow for conditional exit of the loop prematurely. On exiting the loop, execution of the program continues with the line immediately following theNextstatement. For example, the following loop terminates once the program finds a name in themyObjcollection that has fewer than 10 characters:For Each subObject In myObj SName = subObject.NameProperty If Len(Sname) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access