Friday, January 8, 2010

Generate Unique Random Numbers

This UDF will generate x unique random numbers between any 2 numbers you specify.

Function RandLotto(Bottom As Integer, Top As Integer, _

Amount As Integer) As String

Dim iArr As Variant

Dim i As Integer

Dim r As Integer

Dim temp As Integer

Application.Volatile

ReDim iArr(Bottom To Top)

For i = Bottom To Top

iArr(i) = i

Next i

For i = Top To Bottom + 1 Step -1

r = Int(Rnd() * (i - Bottom + 1)) + Bottom

temp = iArr(r)

iArr(r) = iArr(i)

iArr(i) = temp

Next i

For i = Bottom To Bottom + Amount - 1

RandLotto = RandLotto & " " & iArr(i)

Next i

RandLotto = Trim(RandLotto)

End Function

=RandLotto(1,20,8)
This would produce 8 unique random numbers between 1 and 20


Regards,
Praveen KVC
8 January 2010

0 comments:

Post a Comment