Microsoft KB Archive/129450

= PRB: "For Each" Behavior on Dynamically Changing Control Array =

Article ID: 129450

Article Last Modified on 12/9/2003

-

APPLIES TO


 * Microsoft Visual Basic 4.0 Standard Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 16-bit Enterprise Edition
 * Microsoft Visual Basic 4.0 32-Bit Enterprise Edition

-



This article was previously published under Q129450



SYMPTOMS
When using "For Each" to iterate through the elements of a control array that changes dynamically during the execution of the loop, the following unexpected behavior may occur:

 Elements added after the For Each is started are not visited during its execution. Elements deleted after the For Each is started are visited and generate error 340:

Control array element 'n' doesn't exist.





CAUSE
The set of items (to be iterated over by the For Each) is set at the beginning of the iteration. Items added or deleted during the iteration do not affect the set of items iterated over.



STATUS
This behavior is by design.



Steps to Reproduce Behavior
 Start a new project in Visual Basic. Form1 is created by default. Add a Command button (Command1) to your form. Set the Index property of Command1 to 0 (zero). This will create a control array with one element. You then refer to your control as Command1(0).</li>  Add the following code to the Form_Click event of Form1. Sub Form_Click On Error GoTo ErrorHandler Load Command1(1) Load Command1(2) Load Command1(3)

For Each Elt In Command1 Print "This is Command1("; Elt.Index; ")" If Elt.Index = 0 Then Unload Command1(2) Load Command1(4) End If

SkipToHereOnError: Next Exit Sub

ErrorHandler: Print Error$ Resume SkipToHereOnError End Sub </li> Start the program by choosing Start from the Run (or press the F5 key).</li> Click Form1 to run the code in the Click event.</li></ol>

The following will be printed on Form1:

This is Command1(0)

This is Command1(1)

Control array element '2' doesn't exist

This is Command1(3)

NOTE: Attempting to access Command1(2) generates an error because it is unloaded at the first iteration of the loop, and that Command1(4) is not printed.

Additional query words: 4.00 vb4win vb4all

Keywords: kbprb KB129450

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.