在VBA中重复随机数

时间:2014-04-07 09:13:10

标签: excel vba excel-vba random

我在VBA中进行了蒙特卡罗模拟。客户想要(不要质疑为什么)修复随机数序列,即每次运行模型时,序列应保持不变。我设法修改随机种子,如here所述。但它在不同的PC上并不相同。知道为什么以及如何在不同的机器上修复它?

2 个答案:

答案 0 :(得分:3)

您可以使用带有负参数的rnd函数来获得重复的随机数列表。

以下是文档的链接:

http://office.microsoft.com/en-us/access-help/rnd-function-HA001228901.aspx

Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.


Sub TestRandomNumberSequence()

rnd (-10)

    For i = 1 To 5

        Randomize 10
        MsgBox BetweenRange(1, 20, rnd)

    Next i

    'always returns the following sequence

    '5
    '18
    '19
    '6
    '17

End Sub

Function BetweenRange(min As Integer, max As Integer, ByVal rnd As Double) As Integer

BetweenRange = Int((max - min + 1) * rnd + min)

End Function

答案 1 :(得分:1)

根据您的要求,请查看以下链接:

Wabash College Download