I'm new to VBA here. I have 2 lists, a list of price, and a list of the probabilities assigned to the price. I need to generate a list of 300 numbers based on the probability group. However, I can't seem to get it to work. I ripped a code off another post:
Function RandItem(items As Variant, probs As Variant) As Variant
Dim i As Long, sum As Double
Dim spin As Double
spin = Rnd()
For i = LBound(probs) To UBound(probs)
sum = sum + probs(i)
If spin <= sum Then
RandItem = items(i)
Exit Function
End If
Next i
'if you get here:
RandItem = items(UBound(probs))
End Function
And also
Sub test()
Randomize
Dim i As Long, v As Variant
ReDim v(1 To 50)
For i = 1 To 50
v(i) = RandItem(Array(1, 2, 3, 4, 5), Array(0.26, 0.18, 0.26, 0.2, 0.1))
Next i
Debug.Print Join(v)
End Sub
to adapt to my code. However, the problem is that the price range grows, and the probability changes over time (due to historical weightage). So I tried to switch the:
RandItem(Array(1, 2, 3, 4, 5), Array(0.26, 0.18, 0.26, 0.2, 0.1))
to
Dim i As Long, v As Variant
Dim LastRow As Long
Dim arrayPrice As Variant
Dim arrayProPrice As Variant
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
arrayPrice = Range("A2:A" & LastRow).Value2
arrayProPrice = Range("B2:B" & LastRow).Value2
ReDim v(1 To 300)
For i = 1 To 300
v(i) = RandItem(arrayPrice, arrayProPrice)
Next i
Debug.Print Join(v)
End Sub
and it returned: Run-time error '9': Subscript out of range. Anyone has any suggestions how to fix this so I can use array variables instead of listing out all the price ranges?
Credits: Generating numbers with certain probabilities visual basics vba
Aucun commentaire:
Enregistrer un commentaire