Rnd Function

Returns a random number.

Syntax

Rnd[(number)]

Remarks

The argument number can be any valid numeric expression.

The Rnd function returns a Single value less than 1 but greater than or equal to 0.

The value of number determines how Rnd generates a random number:

Value of number                 Number returned

< 0                                       The same number every time, as determined by number.

> 0                                       The next random number in the sequence.

= 0                                       The number most recently generated.

number omitted                    The next random number in the sequence.

The same random-number sequence is generated every time the program is run because each successive call to the Rnd function uses the previous random number as a seed for the next number in the random-number sequence.

To have the program generate a different random-number sequence each time it is run, use the Randomize statement without an argument to initialize the random-number generator before Rnd is called.

To produce random integers in a given range, use this formula:

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

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

Randomize Statement

Math Functions

Rnd Function Example

The example uses the Rnd function to simulate rolling a pair of dice by generating random values from 1 to 6.  Each time this program is run, Randomize uses the Timer function to generate a new random-number sequence.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Dice1, Dice2, Msg              ' Declare variables.

Randomize                          ' Seed random number generator.

Dice1 = Int(6 * Rnd + 1)           ' Generate first die value.

Dice2 = Int(6 * Rnd + 1)           ' Generate second die value.

Msg = "You rolled a " & Dice1

Msg = Msg & " and a " & Dice2

Msg = Msg & " for a total of "

Msg = Msg & (Dice1 + Dice2) & "."

MsgBox Msg                         ' Display message.

End Sub