Generating random but non-repetitive numbers

yxz152830

Active Member
Joined
Oct 6, 2021
Messages
393
Office Version
  1. 365
Platform
  1. Windows
Hey gurus, first one is from a tutorial:
VBA Code:
Function aasd(maxzone, number)

Dim d As New Dictionary
Dim entry As Integer
Application.Volatile
Do
entry = Int(Rnd() * maxzone + 1)
d(entry) = ""
Loop Until d.Count = number
aasd = Application.Transpose(d.Keys)
End Function

I tried different method, are they essentially the same plus I can define the lower bound ? Thanks!
VBA Code:
Function asd(lower, upper, many)
Dim d As New Dictionary
Dim a
Application.Volatile
If many > 1 and upper>many and upper>lower Then
Do
a = Application.WorksheetFunction.RandBetween(lower, upper)
d(a) = ""
Loop Until d.Count = many
Else
End
End If
asd = Application.Transpose(d.Keys)

End Function
 
I tried different method, are they essentially the same plus I can define the lower bound ? Thanks!
VBA Code:
Function asd(lower, upper, many)

Just another option, using collection:
VBA Code:
Function asd(lower, upper, many)
Dim i As Long, x As Long, va
Dim coll As New Collection
    For i = lower To upper
        coll.Add i
    Next
    ReDim va(1 To many)
    For i = 1 To many
        x = WorksheetFunction.RandBetween(1, coll.Count)
        va(i) = coll(x)
        coll.Remove (x)
    Next
asd = Application.Transpose(va)
End Function

To get 10 unique random number between 50 to 100:
VBA Code:
Sub try()
Range("A1:A10") = asd(50, 100, 10)
End Sub
 
Upvote 0

Excel Facts

Enter current date or time
Ctrl+: enters current time. Ctrl+; enters current date. Use Ctrl+: Ctrl+; Enter for current date & time.

Forum statistics

Threads
1,215,833
Messages
6,127,157
Members
449,367
Latest member
w88mp

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top