Rnd 函数Rnd function

返回一个包含伪随机数字的SingleReturns a Single containing a pseudo-random number.


Rnd[(数字)]Rnd [ (Number) ]

可选的_Number_ 参数一个单个或任何有效的数值表达式The optional Number argument is a Single or any valid numeric expression.

返回值Return values

如果_Number_为If Number is 则 Rnd 生成Rnd generates
小于 0Less than zero 使用_number_作为种子时, 每次使用相同的数字。The same number every time, using Number as the seed.
大于 0Greater than zero 伪随机序列中的下一个号码。The next number in the pseudo-random sequence.
等于 0Equal to zero 最近生成的数字。The most recently generated number.
未提供Not supplied 伪随机序列中的下一个号码。The next number in the pseudo-random sequence.


Rnd 函数返回一个小于 1 但大于或等于 0 的值。The Rnd function returns a value less than 1 but greater than or equal to zero.

_Number_的值决定了Rnd生成伪随机数字的方式:The value of Number determines how Rnd generates a pseudo-random number:

  • 对于任何给定的原始种子,由于对 Rnd 函数的每个后续调用会将之前的数字用作序列中的下一个数字的种子,因此,将生成相同的数字序列。For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

  • 在调用 Rnd 之前,请使用不带参数的 Randomize 语句来通过基于系统计时器的种子初始化随机数字生成器。Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

若要生成给定范围中的随机整数,使用此公式:To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

此处,upperbound 是范围中的最大数字,_lowerbound_是范围中的最小数字。Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.


[!注释] 若要重复随机数字的顺序,请先立即调用带负参数的 Rnd ,然后再将 Randomize 与数值参数一起使用。To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. 对_Number_使用具有相同值的随机化不会重复上一个序列。Using Randomize with the same value for Number does not repeat the previous sequence.


此示例使用 Rnd 函数生成一个介于 1 和 6 之间的随机整数值。This example uses the Rnd function to generate a random integer value from 1 to 6.

Dim MyValue As Integer
MyValue = Int((6 * Rnd) + 1)    ' Generate random value between 1 and 6.

另请参阅See also

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.