You can use Rnd and Randomize to generate random numbers. The Rnd Function uses the following syntax:
Rnd()
However, the Rnd Function returns a random number less than one. So, in order to get a whole number, you need to use the Int function. If you need a larger range than 0 or 1, you need to multiply the result.
The following code simulates a dice rolling:
Randomize
Dice1 = Int(5 * Rnd) + 1
Msgbox "You rolled a " & Dice1
the statement Int(5*rnd) generates a number from 0 to 5. You add one after as you cannot role a 0. The Int statement rounds up the number from the Rnd function, as the RND function returns a number less than 1. The Randomize statement initializes the Rnd function. Without this, each time you run your application you will get the same sequence of numbers.
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.
Comments