random?

D

Dave B

Hi,
A friend asked me this question regarding random numbers in VBA
If you run the following code:

Sub rand()
A = 1
For i = 1 To 10
Cells(A, 3) = rnd
A = A + 1
Next i
End Sub

10 random numbers will appear in A1:A10
Now hit the stop (reset) button in the VBA window and run again.
The exact same 'random' numbers appear.

Is this expected?
Is there a work-around?

Regards - Dave.
 
G

Gary Keramidas

you need to use the keyword, randomize .

Sub rand()
A = 1
For i = 1 To 10
Randomize
Cells(A, 3) = Rnd
A = A + 1
Next i
End Sub
 
J

Jim Cone

Even better - place the randomize statement outside of the loop.
--
Jim Cone
Portland, Oregon USA



"Gary Keramidas"
wrote in message
you need to use the keyword, randomize .

Sub rand()
A = 1
For i = 1 To 10
Randomize
Cells(A, 3) = Rnd
A = A + 1
Next i
End Sub
 
D

Dana DeLouis

As a side note, the Worksheet version doesn't need to be Randomized in Excel 2007. Not as efficient though if you have to do this often.
Note that since 'A' & 'i' are equal in your loop, you can eliminate one of the variables.

Sub Demo()
Dim R As Long '(R)ow
For R = 1 To 10
Cells(R, 2) = [Rand()]
Next R
End Sub


A = 1
For i = 1 To 10
A = A + 1
Next i

--
Dana DeLouis
 

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