View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
John Coleman John Coleman is offline
external usenet poster
 
Posts: 274
Default For Each...Next not working

Hi

Are you sure that you read the article correctly? For..Each would
iterate through the *elements* of the array and not their indices.
Run:

Sub test()
Dim A(2) As Integer, e As Variant
A(0) = 3
A(1) = 5
A(2) = 8
For Each e In A
Debug.Print e
Next
End Sub

And you'll see 3,5,8 printed and not 0,1,2
If you want to set each array element equal to its index, use
For..Next:

For i = LBound(A) to UBound(A)
A(i) = i
Next i

HTH

-John Coleman


Lionel H wrote:

MS VBA Help has an article entitled
Using For Each...Next Statements
Which claims
The following code loops through each element in an array
and sets the value of each to the value of the index variable I.
Dim TestArray(10) As Integer, I As Variant
For Each I In TestArray
TestArray(I) = I
Next I
I can't make this work.
I extended the code to read
Sub MS_For_Each_Element_In_Array_Demo()
Dim TestArray(2) As Integer, I As Integer, Element As Variant
For Each Element In TestArray: Debug.Print Element;: Next Element:
Debug.Print
For Each Element In TestArray
TestArray(Element) = I
Debug.Print TestArray(Element);
I = I + 1
Next Element
Debug.Print
For Each Element In TestArray: Debug.Print Element;: Next Element:
Debug.Print
End Sub
Which delivered this to the immediate window:
0 0 0
0 1 2
2 0 0

Is it actually possible to make the For Each...Next construct correctly
populate the elements of an array, and if so, how please?