While reworking an old demo of mine, I came across a function I had created to generate a Random Number between t2o supplied numbers and thought it could help other, so here it is.
'---------------------------------------------------------------------------------------
' Procedure : GetRndNo
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Generate a random number between 2 inputted values
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Uses Late Binding, so none required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' lLowerVal : smallest number of the interval to get a random number from
' lUpperVal : greatest number of the interval to get a random number from
' bInclVals : Should the smallest and greatest numbers be part of the potential returned
' values
'
' Usage:
' ~~~~~~
' lRndNo = GetRndNo(-9, 4)
' Will return a random number between -9 and 4
' lRndNo = GetRndNo(4, -9)
' Will return a random number between -9 and 4
' lRndNo = GetRndNo(4, -9, False)
' Will return a random number between -8 and 3
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
' **************************************************************************************
' 1 2012-02-07 Initial Release
' 2 2018-09-20 Updated Copyright
'---------------------------------------------------------------------------------------
Function GetRndNo(ByVal lLowerVal As Long, ByVal lUpperVal As Long, _
Optional bInclVals As Boolean = True) As Long
On Error GoTo Error_Handler
Dim lTmp As Long
'Swap the lLowerVal and lUpperVal values, if they were inversed in the originating
' function call
If lLowerVal > lUpperVal Then
lTmp = lLowerVal
lLowerVal = lUpperVal
lUpperVal = lTmp
End If
'Adjust the boundary values should the user specify to exclude them from the
' possible returned values
If bInclVals = False Then
lLowerVal = lLowerVal + 1
lUpperVal = lUpperVal - 1
End If
'Calculate our random number!
Randomize
GetRndNo = Int((lUpperVal - lLowerVal + 1) * Rnd + lLowerVal)
Error_Handler_Exit:
On Error Resume Next
Exit Function
Error_Handler:
'LogError Err.Number, Err.Description, sModName & "\GetRndNo", , True, Erl
MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: GetRndNo" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occurred!"
Resume Error_Handler_Exit
End Function