Public Function RandomNumbers(Upper As Integer, Optional Lower As Integer = 1, Optional HowMany As Integer = 1, Optional Unique As Boolean = True) As Variant
On Error GoTo LocalError
If HowMany > ((Upper + 1) - (Lower - 1)) Then Exit Function
Dim x As Integer
Dim n As Integer
Dim arrNums() As Variant
Dim colNumbers As New Collection
ReDim arrNums(HowMany - 1)
With colNumbers
'First populate the collection
For x = Lower To Upper
.Add x
Next x
For x = 0 To HowMany - 1
n = RandomNumber(0, colNumbers.Count + 1)
arrNums(x) = colNumbers(n)
If Unique Then
colNumbers.Remove n
End If
Next x
End With
Set colNumbers = Nothing
RandomNumbers = arrNums
Exit Function
LocalError:
RandomNumbers = ""
End Function
Public Function RandomNumber(Upper As Integer, Lower As Integer) As Integer
Randomize
RandomNumber = Int((Upper - Lower + 1) * Rnd + Lower)
End Function
No comments:
Post a Comment