總份數 = 1+2+3 = 6。生成 0~5 均勻隨機數:
Randomize
Dim r As Integer
r = Int(Rnd() * 6) ' 0~5
Dim result As Integer
Select Case r
Case 0: result = 0
Case 1, 2: result = 1
Case 3, 4, 5: result = 2
End Select
MsgBox result
Function WeightedRandom(weights() As Long) As Integer
Dim total As Long, i As Long
For i = LBound(weights) To UBound(weights)
total = total + weights(i)
Next
Dim r As Long: r = Int(Rnd() * total) + 1
Dim sum As Long
For i = LBound(weights) To UBound(weights)
sum = sum + weights(i)
If r <= sum Then WeightedRandom = i - LBound(weights): Exit Function
Next
End Function
' 調用
Dim w(2) As Long: w(0)=1: w(1)=2: w(2)=3
MsgBox WeightedRandom(w)