JenniferMurphy
Well-known Member
- Joined
- Jul 23, 2011
- Messages
- 2,676
- Office Version
- 365
- Platform
- Windows
I need to write a UDF that will select M numbers from 1 to N randomly without replacement. That is, no duplicates.
I know I can write a loop that will select one random number, check if it has already been selected, repeat if it has. Something like this:
This works, but it could take a while if N is large and M is close to N.
I don't see that either Excel or VBA have a function that will randomly reorder a list. If they do, I could do that and then just take the first M elements.
Thanks
I know I can write a loop that will select one random number, check if it has already been selected, repeat if it has. Something like this:
VBA Code:
Function RandSelect(pM As Double, pN As Double) As Variant
Dim List() As Variant
ReDim List(1 To pN) As Variant
Dim i As Integer
Dim j As Integer
i = 0
RandSelect = ""
Do
j = Int(Rnd() * pN) + 1
If List(j) = 0 Then
List(j) = 1
RandSelect = RandSelect & " " & j
i = i + 1
If i >= pM Then Exit Do
End If
Loop
End Function
This works, but it could take a while if N is large and M is close to N.
I don't see that either Excel or VBA have a function that will randomly reorder a list. If they do, I could do that and then just take the first M elements.
Thanks