This seems to work. However the larger the selection the longer
it takes to fill the array/calculate. It was taking several seconds on 11 cells.
This is not code for a wimpy computer. <g> The array can get quite large...
--
Jim Cone
San Francisco, USA
http://www.realezsites.com/bus/primitivesoftware
Sub WhoIsIt()
MsgBox TipTheScales(Selection)
End Sub
Function TipTheScales(ByRef rng As Excel.Range) As Variant
'Picks a random value using weighted percent values in the selection.
'Percent values should be entered as a whole number.
'Return value is from the cell text directly above the chosen percent value.
'Requires a reference (in the VBE) to ATPVBAIN.XLA in Tools | References
'Jim Cone - San Francisco, USA - December 31, 2006
Dim varArr() As Variant
Dim N As Long
Dim i As Long
Dim j As Long
Dim lngLcm As Long
Dim lngPortion As Long
If Application.Sum(rng) <> 100 Then
TipTheScales = "Selection values must total 100. "
Exit Function
ElseIf rng.Rows.Count <> 1 Then
TipTheScales = "Select only one row. "
Exit Function
Else
For N = 1 To rng.Count
If Not IsNumeric(rng(N)) Then
TipTheScales = "All entries in the selection must be numbers. "
Exit Function
End If
Next
End If
'Least Common Multiple
lngLcm = Lcm(rng)
ReDim varArr(1 To lngLcm, 1 To 2)
For N = 1 To rng.Count
lngPortion = (lngLcm * rng(N).Value) / 100
For i = 1 To lngPortion
varArr(j + i, 1) = rng(N).Value
varArr(j + i, 2) = rng(N).Offset(-1, 0).Value
Next
j = j + lngPortion
Next
'Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
Randomize
N = Int(lngLcm * Rnd) + 1
TipTheScales = varArr(N, 2) & " is a winner. "
End Function
'---------------------
"mslabbe" <
[email protected]>
wrote in message
Well if you can't, you still got farther then I did, lol.
To answer your questions:
the number of fruits is not fixed?
No, they could increase and decrease in different fruit types
the weightings used are not fixed?
No, they will change based on another formula
the data is always laid out in rows with the fruits directly above the percentages?
Yes, the percentages will be below the fruit.
One thing that might help, if I know there will be a max number of
fruit...picking a number, say 18 or 28, would that help? and for the fruit
not in the selection, the percentages are 0% so they would not be selected?
Not sure if that helps
Thanks again
Cheers