bobsan42
Well-known Member
- Joined
- Jul 14, 2010
- Messages
- 2,114
- Office Version
- 365
- 2019
- 2016
- 2013
- Platform
- Windows
it started with a question: http://www.mrexcel.com/forum/showthread.php?t=488078
in short the question was: numbers 1 to 90 ->random list with 30 of them.
then i was really tempted to make a generic solution and i think i did.
Below is a UDF which will generate random integer numbers within chosen limits. If you also decide to fill the Range parameter of the function it will try to generate numbers which are not present in this range. if range is omitted it becomes something like RANDBETWEEN.
When further unique numbers cannot be found (all have been used already) it will return #NOMORE.
so when you use a range like A$1:A2 then filling down will expand the range and you will get a list of unique random numbers.
i did choose not to make it Volatile, but anyone who needs this will know why and how to add it.
any comments, suggestions, etc. are appreciated.
all questions will be answered.
hope someone will find it useful
chrees to all
in short the question was: numbers 1 to 90 ->random list with 30 of them.
then i was really tempted to make a generic solution and i think i did.
Below is a UDF which will generate random integer numbers within chosen limits. If you also decide to fill the Range parameter of the function it will try to generate numbers which are not present in this range. if range is omitted it becomes something like RANDBETWEEN.
When further unique numbers cannot be found (all have been used already) it will return #NOMORE.
so when you use a range like A$1:A2 then filling down will expand the range and you will get a list of unique random numbers.
i did choose not to make it Volatile, but anyone who needs this will know why and how to add it.
Code:
Public Function RandUI42(LowerLimit As Long, UpperLimit As Long, Optional CompareRange As Range) As Variant
Dim ll As Long, ul As Long
ll = Application.WorksheetFunction.Min(LowerLimit, UpperLimit)
ul = Application.WorksheetFunction.Max(LowerLimit, UpperLimit)
If CompareRange Is Nothing Then
RandUI42 = Round(ll + (ul - ll) * Rnd(), 0)
Exit Function
End If
For i = ll To ul Step 1
If Application.WorksheetFunction.CountIf(CompareRange, i) = 0 Then
RandUI42 = Round(ll + (ul - ll) * Rnd(), 0)
Do While Application.WorksheetFunction.CountIf(CompareRange, RandUI42) > 0
RandUI42 = Round(ll + (ul - ll) * Rnd(), 0)
Loop
Exit Function
End If
Next i
RandUI42 = "#NOMORE"
End Function
any comments, suggestions, etc. are appreciated.
all questions will be answered.
hope someone will find it useful
chrees to all