Table of Contents

5.4.2.4 For Each Statement

Note

This section describes the implementation of MS-VBAL §5.4.2.4 For Each Statement.

Syntax

AST node Instruction kind(s) Notes
ForEachStatementNode ForEachOpener The For Each opener. Its End is the offset right past the Next closer.
None (synthesized) ForEachNext The Next closer; Node is null. Its Target is the body's first instruction; its Matching is the offset of its ForEachOpener.

The resolved targets have the same shape as a For loop's (RD-VBAL §5.4.2.3 For Statement; RD-VBAL §3.5.2 Instruction).

Static Semantics

MS-VBAL requires the For Each collection to be an array or an enumeration-capable object reference. What MS-VBA refuses, RD-VBA refuses the same way (recorded in Excel):

The collection is Example Error
No name, member or call: a literal, an operator's result, anything in parentheses For Each v In 5, For Each v In "abc", For Each v In (a) VBC00001 Syntax error
A value of an intrinsic type, or a record For Each v In n, of a Long; For Each v In LongFn(); For Each v In q, of a Type VBC09379 For Each may only iterate over a collection object or an array
A project, a module or an Enum type For Each v In Strings, For Each v In Color VBC09379

A Variant is iterated as what it holds when the loop runs: one that holds no array and no object is run-time error 13, and a Next reached after it is run-time error 92 (see Errors).

An object of an enumerable class can be efficiently iterated using a For Each...Next loop. For Each...Next enumeration is intended to be used with collections containing objects (RD-VBAL §2.4.2.3 Enumerable Class Types).

Runtime Semantics

For Each is implemented for arrays and for objects that expose an enumeration member.

A language-level condition in a well-formed program never reports InternalError; such a condition raises a run-time error.

ForEachOpener

  1. Evaluate the collection expression once.
  2. When the collection is a Variant holding an array, unwrap it: For Each x In v enumerates a Variant holding an array in the same way as a declared array.
  3. When the collection is a VBArrayValue:
    1. If the array was never initialized (VBArrayValue.IsInitialized is false: a Dim with no bounds, never ReDim'd), raise error 92.
    2. If the array's declared bounds hold zero elements, empty the control variable (see The control variable after the loop) and skip the body entirely by branching to Instruction.End, per MS-VBAL §5.4.2.4's "if the array has no elements".
    3. Otherwise, assign the first element to the control variable, store a ForEachState, and fall through into the body. The assignment is a Set-assignment when the array's item type is Object, and a Let-assignment otherwise (MS-VBAL §5.4.2.4's rule).
  4. When the collection is Nothing, raise error 91: enumerating it would invoke _NewEnum on an unset reference.
  5. When the collection is a live object whose class exposes a member with VB_UserMemId = -4 (commonly _NewEnum), invoke that member and store a ForEachState holding the enumerator object it returns (see Object enumeration below), then ask the enumerator for its first member as an array's first element is taken. When it has none, empty the control variable and skip the body. The member's declared type may be IUnknown, Object or the enumerator's own class.
  6. When the collection is a live object with no such member, raise error 438.
  7. When the collection is anything else (a scalar), raise error 13, TypeMismatch.

ForEachNext

  1. Read the ForEachState back via Instruction.Matching.
  2. Advance the index (an array), or ask the enumerator for its next member (an object). When the array or the enumerator is exhausted, empty the control variable and fall through past the loop.
  3. Otherwise, assign the next element to the control variable, and branch back to the body's first instruction (Instruction.Target).

Object enumeration

MS-VBAL leaves the enumeration of an object implementation-defined. RDCore follows the shape of COM's IEnumVARIANT, reduced to the two members a VBA enumerator is written with:

Member Contract
MoveNext() As Boolean Advances to the next member; False when there is none.
Current As Variant The member the enumerator is at.

The enumerator of a Collection (IEnumVARIANT) is a library class that has them, and so is an enumerator written in VBA: a class whose _NewEnum (VB_UserMemId = -4) returns Me, or any other object that has the two. Each loop has an enumerator of its own, so loops over the same object, nested or in turn, do not disturb one another; a member added to a Collection while a loop runs is not the loop's.

RD-VBA differs from MS-VBA: a loop holds the object it walks until it is over. A Set to Nothing of the variable named after In, inside the loop (Set c = Nothing in For Each v In c), leaves the variable as it is while the loop runs: the loop reaches every member, and the variable still refers to the object after it. MS-VBA lets go of a Collection there, which is destroyed with the members the loop has not reached, and the loop ends. RDC11035 warns at such a Set.

A member is Set-assigned to the control variable when it is an object and the control variable can hold one, and Let-assigned otherwise: a Long control is Let-coerced from a member that is a number.

IUnknown is a library class (IStdUnknownClass), the root interface: an object of any class is one in a Set assignment, as it is an Object, which is what lets Property Get NewEnum() As IUnknown be written as it always has been. The VB_UserMemId of a class module's member travels in the symbol descriptor (SymbolDescriptor.UserMemId), so the host finds the enumeration member and the default member of a workspace class as it does those of the library's.

The control variable after the loop

MS-VBAL §5.4.2.4 says that once the loop has finished, the control variable holds the last element of the array or the collection. MS-VBA does not keep it: a loop that runs out empties its control variable, which is then Empty, or Nothing for an object variable. Neither MS-VBAL nor the MS Learn page of the For Each...Next statement mentions this. RD-VBA does what MS-VBA does. These are the cases recorded in Excel:

How the loop ends The control variable after it
The array or the collection runs out, in the procedure itself or in a procedure it calls. Empty, or Nothing for an object variable.
The array or the collection has no element: Array(), Split(""), an empty Collection. Empty, or Nothing.
The body assigns the control variable, then the loop runs out. Empty: the assigned value is lost.
Exit For, a GoTo out of the loop, Exit Sub, an error handled outside the loop or raised to the caller, even on the last element. The element the loop was at.
A Next finds no loop running (error 92), and the control variable is a Variant. Empty, unless the collection is declared as an array: then it is left as it was.
A Next finds no loop running (error 92), and the control variable is an object variable. Left as it was.

A ByRef parameter used as the control variable empties the caller's variable. The rule is the same for a module variable, a local and a Static local, and for a Variant declared As Variant or with no type.

RDC11032 warns where the control variable is read after a loop that can only have run out (RD-VBAL §2.6.4 Rubberduck Core Diagnostics).

MS-VBA also refuses a control variable of any type other than Variant and Object: For Each s In c, with s a String and c a Collection, is the compile error For Each control variable must be Variant or Object. MS-VBAL asks for a Variant only when the collection is declared as an array.

Note

Not implemented. RD-VBA accepts a control variable of another type, and empties it with a Let-assignment of Empty.

Errors

Condition Run-time error
The collection is an array that was never initialized (VBArrayValue.IsInitialized is false). 92 (For loop not initialized)
ForEachNext finds no stored ForEachState for its Matching offset: a GoTo landed in the body or on the closer, or the opener raised an error that was resumed past. A Variant control variable is emptied first, unless the collection is declared as an array. 92 (For loop not initialized)
The collection is Nothing. 91 (Object variable or With block variable not set)
The collection is a live object with no VB_UserMemId = -4 member, or the enumerator it returns has no MoveNext and Current. 438 (Object doesn't support this property or method)
The collection is anything else (a scalar). 13 (Type mismatch)

MS-VBAL does not separately call out an array that was never initialized. MS-VBA raises error 92 for it, because the collection itself was never set up; a declared array with zero elements is the "no elements" case instead.

MS-VBAL requires the collection to be an array or an enumeration-capable object reference, so errors 91, 438 and 13 are the specified outcomes. The error identifiers are listed in RD-VBAL §2.6.3 Runtime Errors.

5.4.2.4.1 Array Enumeration Order

Note

This section describes the implementation of MS-VBAL §5.4.2.4.1 Array Enumeration Order.

The element block of an array value is stored and addressed in column-major order, which is the traversal order MS-VBAL §5.4.2.4.1 mandates: the first subscript varies fastest, matching an OLE SAFEARRAY (RD-VBAL §2.5.2.1.2 Array Values).

VBArrayValue.ElementAt(flatIndex) therefore walks the array in enumeration order directly, with no per-dimension subscript arithmetic. The index a ForEachState holds is this flat index.

Implementation