PDA

View Full Version : Solved: Random Numbers Repeating



tammyl
08-02-2009, 09:21 PM
Hi,

I have this random number function (Rnd) called from my 'Main' worksheet vba code. When I run the Main code, the Rnd script will loop about 30 times. Each loop generates a random number and gets the relevant notation from one worksheet and copies to another worksheet.
Perfect.



Dim Low As Double
Dim High As Double
Application.Volatile
Low = 3 '<<<< CHANGE
High = 130 '<<<< CHANGE
dRand = Round(Rnd * (High - Low) + Low, 0)


My problem is; if I then re-run the Main code for the worksheet, the 30 random numbers generated are exactly the same 30 numbers, in exactly the same order from the previous time i ran the 'Main' code regardless of opening/closing workbook, etc.

How can I ensure that each time I run the 'Main' script the random numbers are 'random' and not the same all the time.

Hope someone can help.

Cheers
tammyl

GTO
08-02-2009, 11:18 PM
Hi Tammy,

As you are looping thru it, I'm guessing it's not being used as a user defined function, so I'm not sure the Volatile is advantageous. Regardless of that, at least according to the help file's example, there's a missing +1 and I think you want to add in a Randomize to give it a seed value.

Try:

'Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Function GetRnd() As Long
Const LOW As Long = 3
Const HIGH As Long = 130

Randomize
GetRnd = Int((HIGH - LOW + 1) * Rnd + LOW)
End Function

Sub Fill30Rows()
Dim i As Long
For i = 1 To 30
ActiveCell.Value = GetRnd
ActiveCell.Offset(1).Select
Next
End Sub


Does that help?

Mark

tammyl
08-02-2009, 11:59 PM
Thank you very much Mark.

I had that formula as my first attempt but still got the repetition.
The 'Randomize' seems to have made the difference.
It is now generating a different set of 30 numbers each time I run the Main Code.

Problem Solved.
Thanks again.
Cheers
tammyl