View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Rick Rothstein \(MVP - VB\) Rick Rothstein \(MVP - VB\) is offline
external usenet poster
 
Posts: 2,202
Default Picking a random number from data

I have a series of data in rows and columns in excel 5x10
and I would like to randomly pick 5 numbers from this data.
Can this be done? If so how?


You can use the function below my signature to get what you are asking
about. Pass in a range covering the cells holding your data and the number
of values you want randomly returned from that range and the function will
return a Variant containing an array with those values. Here is a sample
code snippet (using an example CommandButton to kick everything off with)
showing this function in use (I used Selection for the range, but you should
supply your actual range in its place)...

Private Sub CommandButton1_Click()
Dim X As Long
Dim Msg As String
Dim Result As Variant
Result = RandomPick(Selection, 5)
For X = LBound(Result) To UBound(Result)
Msg = Msg & Result(X) & vbCrLf
Next
MsgBox Msg
End Sub

I didn't add any error checking, so you should consider doing so. At a
minimum, you'll want to make sure more items weren't requested than cells in
the range.

Rick


Function RandomPick(Rng As Range, HowMany As Long) As Variant()
Dim R As Range
Dim X As Long
Dim RandomIndex As Long
Dim TempElement As Variant
Dim Values() As Variant
Dim Answer() As Variant
Static RanBefore As Boolean
If Not RanBefore Then
RanBefore = True
Randomize
End If
ReDim Values(0 To Rng.Count - 1)
For Each R In Rng
Values(X) = R.Value
X = X + 1
Next
If VarType(Values) = vbArray Then
For X = UBound(Values) To LBound(Values) Step -1
RandomIndex = Int((X - LBound(Values) + 1) * _
Rnd + LBound(Values))
TempElement = Values(RandomIndex)
Values(RandomIndex) = Values(X)
Values(X) = TempElement
Next
End If
ReDim Answer(0 To HowMany)
For X = 0 To HowMany - 1
Answer(X) = Values(X)
Next
RandomPick = Answer
End Function