Random numbers are necessary if you plan to program many things. Visual Basic provides an easy way to generate a random number any time you desire. Before you generate the random number you should use the Randomize statement. If you do not, it pulls the numbers from a list, meaning that each time you run the program you will get the same numbers. Finally, Rnd will generate the random number. Do as follows:
Dim Number, Lowest, Highest As Integer
Lowest = 5
Highest = 20
Randomize
Number = Int((Highest - Lowest + 1) * Rnd + Lowest)
Lowest is the lowest number that the random number can be. We will put it in the randomizing statement later. I gave it a value of 5, but of course you can change that. Highest is the highest number. I gave it a value of 20, but of course you can change that too. You already know what randomize does. Now look at the last line after the equal sign. Int rounds the number off. The Highest - Lowest + 1 tells the randomizing statement what the highest number it can generate is. * Rnd creates the random number. + Lowest gets added to the Rnd number and keeps it from being below the set lowest number.
If you ran this code it would assign a random number, 5 - 20, to the variable Number. This is pretty self-explainatory from here on out. If you like, you can download the example program here.
Copyright ©2000 by Kyle Baker. Please read our disclaimer.