Array Question

F

Frederick Chow

Hi all,

I have a problem about looping arrays. Consider the following program:

Sub Testing2()
Dim X(1 To 8) As Long
Dim i As Long
For i = LBound(X) To UBound(X)
X(i) = Rnd * 10000
Next

X will contain the random number as expected. However if I use FOR EACH
loop,

Sub Testing2()
Dim X(1 To 8) As Long
Dim Element As Variant
For Each Element in X
Element = Rnd * 10000
Next

Then the each array element still contains 0! Why is that? Please advise.

Frederick Chow
Hong Kong.
 
T

Tom Ogilvy

Sub Testing2()
Dim X(1 To 8) As Long
Dim i As Long
Dim Element As Variant

For i = LBound(X) To UBound(X)
X(i) = Rnd * 10000
Next

For Each Element In X
Debug.Print Element
Next
End Sub

works, but I can't say why it doesn't work for assignment. I do know I have
seen an MS KB article that advises against using For ... Each with an array.
Maybe this is why.

Generally, I find it is easier to use what works than to wonder why.
 
F

Frederick Chow

Frederick Chow said:
Hi all,

I have a problem about looping arrays. Consider the following program:

Sub Testing2()
Dim X(1 To 8) As Long
Dim i As Long
For i = LBound(X) To UBound(X)
X(i) = Rnd * 10000
Next

X will contain the random number as expected. However if I use FOR EACH
loop,

Sub Testing2()
Dim X(1 To 8) As Long
Dim Element As Variant
For Each Element in X
Element = Rnd * 10000
Next

Then the each array element still contains 0! Why is that? Please advise.

Frederick Chow
Hong Kong.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top