Dim myNumber as Long
Randomize
myNumber=INT(RND * 10)+1
myNumber = INT(RND * the number of items) + lowest number
myNumber=INT(RND * 8)+3
Sub From_Hat()
'Declare the collection
Dim myHat As New Collection
Dim names() As String
Dim x As Long
Dim iChoice As Integer
'load names (or numbers) into an array using SPLIT
'you can use a longer list!
names = Split("Bob\Mary\Joe\John", "\")
'Bob will be names(0) and John names(3)
'load into the new collection
For x = 0 To UBound(names)
myHat.Add (names(x))
Next x
Do
Randomize
'choose a random name
iChoice = Int(Rnd * myHat.Count) + 1
MsgBox myHat(iChoice)
'remove that choice
myHat.Remove (iChoice)
Loop Until myHat.Count = 0
MsgBox "All chosen"
End Sub
You should be able to modify the code easily to create other similar simulations.
If you need a range of numbers instead of names then you can omit the array and slit and just use a simple loop to load the collection.
e.g.
'load into the new collection
For x = 1 To 99
myHat.Add (x)
Next x
Do
Randomize
'choose a random name
iChoice = Int(Rnd * myHat.Count) + 1
If MsgBox("The choice is " & myHat(iChoice) _
& vbCrLf & "Choose again?", vbYesNo) <> vbYes Then Exit Do
'remove that choice
myHat.Remove (iChoice)
Loop Until myHat.Count = 0
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)