O'Reilly logo

VBScript in a Nutshell, 2nd Edition by Ron Petrusha, Matt Childs, Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

For Each . . . Next Statement

Syntax

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

Use: Required

Data Type: Variant

A variable 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 if group contains at least one element.

  • All statements are executed for each element in group in turn until either there are no more elements in group, or the loop is exited prematurely using the Exit For statement. Program execution then continues with the line of code following Next.

  • For Each...Next loops can be nested, but each element must be unique. For example:

    For Each myObj In anObject
       For Each subObject In myObject
          sName(ctr) = subObject.NameProperty
          ctr = ctr + 1
       Next
    Next

    uses a nested For Each...Next loop, but two different variables, myObj and subObject, represent element.

  • Any number of Exit For statements can be placed with the For 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 the Next statement. For example, the following loop terminates once the program finds a name in the myObj collection that has fewer than 10 characters:

    For Each subObject In myObj SName = subObject.NameProperty If Len(Sname) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required