This is a simple VB6 function to generate random numbers in the specified range, without repeating any numbers.
New, and only briefly tested. Use at your own risk. :)
- Option Explicit
-
-
Private UsedNumber As New Collection
-
Private Const MaxAttempts As Long = 150
-
Private Const Zero As Long = 0
-
Private Const One As Long = 1
-
-
Public Function RandomNonRepeatingBetween(ByVal LowerLimit As Long, ByVal UpperLimit As Long) As Long
-
' Generate a pseudo-random number between the specified bounds.
-
' Never return one which has already been used.
-
' Don't forget to use Randomize at least once before calling
-
' this function (but not EVERY time, if calling repeatedly).
-
-
' The record of used numbers will be cleared only when the
-
' caller specifically requests it by passing zero as both the
-
' upper and lower bounds.
-
-
' If it is not possible to satisfy the request (for instance,
-
' if all numbers in the requested range have already been
-
' used, then error 17 ("Can't perform requested operation")
-
' will be raised. Caller should allow for this and handle
-
' it as appropriate.
-
-
' Note, for the moment it will simply try up to 150 times, I
-
' haven't worked out the code yet to do a proper check for
-
' whether any numbers are left in the range.
-
-
' If lower/upper limit are backward, swap them around.
-
Dim Temp As Long
-
Dim Attempts As Long
-
-
If LowerLimit > UpperLimit Then
-
Temp = LowerLimit
-
LowerLimit = UpperLimit
-
UpperLimit = Temp
-
End If
-
-
' Clear memory if caller requests it.
-
If LowerLimit = Zero And UpperLimit = Zero Then
-
Do While UsedNumber.Count > Zero
-
UsedNumber.Remove One
-
Loop
-
End If
-
-
On Error Resume Next
-
Do
-
Temp = LowerLimit + Rnd * (UpperLimit - LowerLimit)
-
UsedNumber.Add Temp, Format(Temp)
-
If Err.Number = Zero Then
-
RandomNonRepeatingBetween = Temp
-
Exit Do
-
End If
-
Err.Clear
-
Attempts = Attempts + One
-
Loop While Attempts < MaxAttempts
-
Err.Clear
-
On Error GoTo 0
-
End Function