Copy the following code into a module and you have a ready to go integer random number generator (the numbers are integer in the mathematical sense of the word, their type is a long VB variable). Coding should be self-explanatory.
Private Enum rvbErrorDataGenval
rvbNull = 0
rvbInfinite
rvbIndefinitive
rvbOutOfBounds
rvbUpperLTLower
End Enum
Private Const c_rvbUpperBoundRandomLong As Long = 2147483647
Private Const c_rvbLowerBoundRandomLong As Long = 1
Public Function RandomNumber(Optional ByVal lngUpperBound As Long = c_rvbUpperBoundRandomLong, _
Optional ByVal lngLowerBound As Long = c_rvbLowerBoundRandomLong) As Long
'*Purpose : Generate a random number within given bounds
'*Accepts : Two optional long values, the first being the UPPER bound,
'* the second one being the lower bound. The lower bound should
'* be greater than zero
'* REMARK: default lower bound is 1 (ONE)
'*Returns : The random number
'* ZERO - the upper bound is not greater than the lower bound
'* - one of the bounds is negative or zero
'*REMARK : Before using the function you should issue the Randomize statement
'* to generate different random numbers from one run to another
Dim intMyErrorNumber As rvbErrorDataGenval
'Bounds must be positive
If lngUpperBound < 0 Or lngLowerBound <= 0 Then
intMyErrorNumber = rvbOutOfBounds
GoTo PROC_ERROR
End If
'Make sure Upperbound > Lowerbound
If lngUpperBound <= lngLowerBound Then
intMyErrorNumber = rvbUpperLTLower
GoTo PROC_ERROR
End If
RandomNumber = Fix((lngUpperBound - lngLowerBound + 1) * Rnd + lngLowerBound)
PROC_EXIT:
Exit Function
PROC_ERROR:
Select Case intMyErrorNumber
Case rvbOutOfBounds
MsgBox "Upper and/or Lower Interval limits" & vbCrLf & _
"must be greater than zero", , App.Title
Case rvbUpperLTLower
MsgBox "Upper interval limit should be greater" & vbCrLf & _
"than Lower interval limit", , App.Title
Case Else
MsgBox "Unknown error. Should not really occur", , App.Title
End Select
RandomNumber = 0
GoTo PROC_EXIT
End Function
_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]