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
- Evaluate the collection expression once.
- When the collection is a
Variantholding an array, unwrap it:For Each x In venumerates aVariantholding an array in the same way as a declared array. - When the collection is a VBArrayValue:
- If the array was never initialized (
VBArrayValue.IsInitializedis false: aDimwith no bounds, neverReDim'd), raise error 92. - 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". - 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).
- If the array was never initialized (
- When the collection is
Nothing, raise error 91: enumerating it would invoke_NewEnumon an unset reference. - When the collection is a live object whose class exposes a member with
VB_UserMemId = -4(commonly_NewEnum), invoke that member and store aForEachStateholding 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 beIUnknown,Objector the enumerator's own class. - When the collection is a live object with no such member, raise error 438.
- When the collection is anything else (a scalar), raise error 13,
TypeMismatch.
ForEachNext
- Read the
ForEachStateback viaInstruction.Matching. - 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.
- 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
ProcedureExecutor.ExecuteForEachOpenerunwraps a VBVariantValue before matching a wrapped array (RD-VBAL §5.5.1.2 Runtime semantics, Let-coercion to Variant).ForEachOpenerstores aForEachStateholding the control symbol and expression, the array, and a flat index. The state is read via ICallStackFrame.TryGetForEachState, and written viaCallStackFrame.SetForEachState.- A
For Eachloop's state is an enumeration cursor, so it has its own type,ForEachState(RD-VBAL §3.5.4 Execution). ForEachNextreads the state back viaInstruction.Matching, the same field thatForNextandCaseheaders use.- The enumeration-member lookup uses
VBReturningMemberSymbol,
SymbolProperties
.UserMemIdand WellKnownDispIds.NewEnumon the class of the object (RD-VBAL §6.1.3.1 Collection Object). - A plain array-typed variable read back as an expression
(SimpleNameExpressionNode, the ordinary
shape of
arrinFor Each item In arr) yields the array value stored in it: VBArrayType.CreateValueunboxes the VBRuntimeArrayValue thatSymbolAddressTableboxed for the variable, and returns the same instance with its cells intact (RD-VBAL §2.5.2.1.2 Array Values).