简体   繁体   English

VBA中的随机数生成器,使用Analysis Toolpack-VBA

[英]Random number generator in VBA using Analysis Toolpack-VBA

I use the following line to generate Poisson random numbers: 我使用以下行生成泊松随机数:

Application.Run("Random", "", 1, 100, 5, , 34) 

this produces 100 random numbers with Lambda (34) in an excel sheet. 这会在excel表中生成100个Lambda(34)的随机数。 I would like to save the output into a variable instead of sheet. 我想将输出保存到变量而不是表单。 I tried 我试过了

X=Application.Run("Random", "", 1, NSim, 5, , 34)

I don't get any error but nothing is saved in "X". 我没有收到任何错误,但“X”中没有保存任何内容。 Could you please help me how I can save the result in a variable. 你能帮我解决一下我如何将结果保存在一个变量中的问题。 Thanks 谢谢

看起来该函数返回一个布尔值而不是一个数字数组,并且只接受一个范围作为输出作为其参数之一。

It looks like Random is a sub routine, unless you have access to the underlying code you can't do this directly. 看起来Random是一个子例程,除非您有权访问底层代码,否则无法直接执行此操作。

What you could do (albeit rather backwards) is let the sub run, then assign the result back to a variable and remove it from the sheet: 您可以执行的操作(尽管相当向后)是让子运行,然后将结果分配回变量并将其从工作表中删除:

Sub MM()
    Dim generateNumbers As Integer, results As Variant
    generateNumbers = 100 '// numbers to generate

    Application.Run("Random", "", 1, generateNumbers, 5, , 34)

    results = WorksheetFunction.Transpose(Range("A1:A" & generateNumbers))
    Range("A1:A" & generateNumbers).ClearContents '// If required
End Sub

The variable results will now be an array of the results. 变量results现在将是结果的数组。

How about: 怎么样:

Sub MAIN()
   Dim x(1 To 100) As Variant
   Dim Lambda As Double
   Lambda = 34

   For I = 1 To 100
      x(I) = Poisson(Lambda)
   Next I

End Sub


Public Function Poisson(L As Double) As Long
   Dim I As Long, x As Double, expL As Double

   expL = Exp(-L)
   I = 0
   x = 1
   While x > expL
      I = I + 1
      x = x * Rnd()
   Wend
   Poisson = I - 1
End Function

Although it is poissonous, it's not toxic. 虽然它很有趣,但它没有毒性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM