Number Functions

Random Numbers

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.

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.”