Name
For Each...Next Statement
Syntax
For EachelementIngroup[statements] [Exit For] [statements] Next [element]
-
element(required; Object or any user-defined object type) An object variable to which the current element from the group is assigned
-
group(required) An object collection or array
-
statements(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
ForEach...Nextcode block is executed only ifgroupcontains at least one element. Ifgroupis an empty collection or an array that has not yet been dimensioned, an error (runtime errors 92, “For loop not initialized,” and 424, “Object required,” respectively, or a NullReferenceException exception) results.All
statementsare executed for eachelementingroupin turn until either there are no more elements ingroupor 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
myObjIn AnObject For EachsubObjectIn myObj SName = subObject.NameProperty Next Nextuses a nested
ForEach...Nextloop, but two different variables,myObjandsubObject, representelement.Any number of
ExitForstatements can be placed within theForEach...Nextloop to allow for premature, conditional exit of the loop. Once the loop is exited, execution of the program continues ...
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