PDA

View Full Version : [SOLVED] Randomize



gibbo1715
09-06-2005, 12:46 AM
Can some one give me a quick piece of code that will randomly generate 1000 different numbers between 20000 and 30000 please

cheers

gibbo

Jacob Hilderbrand
09-06-2005, 12:53 AM
Try this.



Option Explicit

Sub RandomNumbers()
Dim n As Long
Dim MinValue As Long
Dim MaxValue As Long
Dim i As Long
Dim RandomNumber As Long
n = 1000
MinValue = 20000
MaxValue = 30000
Randomize
For i = 2 To n + 2
Do
RandomNumber = Int((MaxValue - MinValue + 1) * Rnd + MinValue)
If Application.WorksheetFunction.CountIf(Range("A1:A" & i - 1), RandomNumber) = 0 Then
Range("A" & i).Value = RandomNumber
Exit Do
End If
Loop
Next i
End Sub

gibbo1715
09-06-2005, 01:01 AM
Thanks Jake, just the job

Jacob Hilderbrand
09-06-2005, 01:02 AM
You're Welcome :beerchug:

Take Care

MWE
09-06-2005, 06:09 AM
Try this.


Option Explicit

Sub RandomNumbers()

Dim n As Long
Dim MinValue As Long
Dim MaxValue As Long
Dim i As Long
Dim RandomNumber As Long

n = 1000
MinValue = 20000
MaxValue = 30000
Randomize
For i = 2 To n + 2
Do
RandomNumber = Int((MaxValue - MinValue + 1) * Rnd + MinValue)
If Application.WorksheetFunction.CountIf(Range("A1:A" & i - 1), RandomNumber) = 0 Then
Range("A" & i).Value = RandomNumber
Exit Do
End If
Loop
Next i

End Sub


further to DRJ's code, note the Randomize statement.

Most random number generators produce "pseudo" random numbers (not perfect, but good enough for virtually any application we might have) and normally produce the SAME random number sequence each time the random number generator is started. To ensure that each sequence is random and different, one normally grabs the system date and time and uses it to generate a random number "seed" (starting point). That is what the Randomize statement does.