Choose a Random Number from a List
This code is the equivalent of choosing a numbered ball from a bag of balls
where the numbers are not sequential. It can be easily altered to choose a
name.
Sub Pick_Number()
'Must be a dynamic array ie no range
Dim MyNums() As String
Dim Inum As Integer
Dim Ichosen As Integer
'load list into Array based on split by /
'note will start as MyNums(0) and finish with MyNums(number-1)
MyNums = Split("1/5/11/17/21", "/")
Randomize
'This will work with any length of number sequence
Ichosen = Int(Rnd * (UBound(MyNums) + 1))
Inum = CInt(MyNums(Ichosen))
MsgBox Inum
End Sub
Sub Pick_Name()
'Must be a dynamic array ie no range
Dim MyNames() As String
Dim strName As String
Dim Ichosen As Integer
'load list into Array based on split by /
'note will start as MyNums(0) and finish with MyNums(number-1)
MyNames = Split("John/Bill/Fred", "/")
Randomize
'This will work with any length of number sequence
Ichosen = Int(Rnd * (UBound(MyNames) + 1))
strName = MyNames(Ichosen)
MsgBox strName
End Sub
This code can also be adapted to choose names one by one with no
repetition
Sub Pick_Name()
'Must be a dynamic array ie no range
Dim MyNames() As String
Dim strName As String
Dim Ichosen As Integer
'load list into Array based on split by /
'note will start as MyNums(0) and finish with MyNums(number-1)
MyNames = Split("John/Bill/Steve/Echo/Sandy", "/")
Do
Randomize
'This will work with any length of name sequence
Ichosen = Int(Rnd * (UBound(MyNames) + 1))
strname = (MyNames(Ichosen))
MsgBox strName
'move top num,ber into chosen slot
MyNames(Ichosen) = MyNames(UBound(MyNames))
If UBound(MyNames) > 0 Then
'delete top number
ReDim Preserve MyNames(0 To UBound(MyNames) - 1)
Else
MsgBox "All chosen"
Exit Sub
End If
Loop Until MsgBox("Another", vbYesNo) = vbNo
End Sub
|