在VBA中编写函数以返回三角形随机数

时间:2016-10-28 23:08:19

标签: excel vba excel-vba function random

我正在尝试为excel编写一系列VBA函数,这些函数将返回随机数类型以在子例程中调用。一旦我进入更复杂的公式,我会遇到类似的错误。例如:不对称三角形随机变量。

这是功能:

Function AsymetricTriangleInVBA (min As Double, mode As Double, max As Double) As Double
  Application.Volatile
  Randomize
  Dim Temp As Variant
  Temp = Rnd
  AsymetricTriangleInVBA = WorksheetFunction.if(Temp < ((mode - min) / (max - min)), min + (max - min) * WorksheetFunction.sqrt(((mode - min) / (max - min)) * Temp), min + (max - min) * (1 - WorksheetFunction.sqrt((1 - ((mode - min) / (max - min))) * (1 - Temp))))
End Function

'my test sub

Sub test()
    MsgBox AsymetricTriangleInVBA(5, 10, 15)
End Sub

我收到的一致错误是:

  

运行时错误'438':   Object不支持此属性或方法

这个错误意味着什么,我该如何解决?

1 个答案:

答案 0 :(得分:2)

每当VBA本身有等价物时,我通常不会使用WorksheetFunction ......在这种情况下SQR

我认为有两种方法可以使它发挥作用..

1)

Function AsymetricTriangleInVBA(min As Double, mode As Double, max As Double) As Double
  Application.Volatile
  Dim intCondition As Integer
  Randomize
  Dim Temp As Variant
  Temp = Rnd
  intCondition = CInt(Temp < ((mode - min) / (max - min))) * -1
  AsymetricTriangleInVBA = intCondition * (min + (max - min) * Sqr(((mode - min) / (max - min)) * Temp)) + (1 - intCondition) * (min + (max - min) * (1 - Sqr((1 - ((mode - min) / (max - min))) * (1 - Temp))))
End Function

2)

Function AsymetricTriangleInVBA(min As Double, mode As Double, max As Double) As Double
  Application.Volatile

  Randomize
  Dim Temp As Variant
  Temp = Rnd

    If Temp < ((mode - min) / (max - min)) Then
        AsymetricTriangleInVBA = (min + (max - min) * Sqr(((mode - min) / (max - min)) * Temp))
    Else
        AsymetricTriangleInVBA = (min + (max - min) * (1 - Sqr((1 - ((mode - min) / (max - min))) * (1 - Temp))))
    End If


End Function