使用VBA的离散函数

时间:2016-07-04 16:45:50

标签: excel-vba montecarlo vba excel

我正在尝试使用VBA代码创建Discrete函数 它有时会工作,但我也收到了“范围错误的下标”消息。任何人都可以找出原因吗?

Function Discrete6()    
    Dim value As Variant, prob As Variant, i As Integer
    Dim uniform As Double, cumProb As Variant

    value = Array(5, 10, 12)
    prob = Array(0.2, 0.3, 0.5)
    uniform = Rnd
    cumProb = prob(1)

    i = 1
    Do Until cumProb > uniform
        i = i + 1
        cumProb = cumProb + prob(i)
    Loop

    Discrete6 = value(i)
End Function

1 个答案:

答案 0 :(得分:0)

以下修改有点脏,但它适用于您的特定情况(具有3个成员的数组)。

Function Discrete6()

Dim value As Variant, prob As Variant, i As Integer
Dim uniform As Double, cumProb As Variant

value = Array(5, 10, 12)
prob = Array(0.2, 0.5, 1)
uniform = Rnd

Select Case uniform
    Case Is <= prob(0)
        Discrete6 = value(0)
    Case Is > prob(1)
        Discrete6 = value(2)
    Case Else
        Discrete6 = value(1)
End Select

End Function