|From John Slaughter
If you use random numbers to a large extent, you probably get tired of always having to put in Randomize and then the equation. This simple subroutine handles both chores for you. First, put the following routine in your project's main module.
Public Function GenRndNumber(Upper As Integer, Lower As Integer) As Integer
GenRndNumber = Int((Upper - Lower + 1) * Rnd + Lower)
To get a random number between 99 and -99, just enter:
RandomNumber = GenRndNumber(99, -99)
You can get a random letter between "A" and "M" with this:
RandomLetter = Chr$(GenRndNumber(asc("M"), asc("A")))
You can eliminate the middle of a range by putting the call to GenRndNumber inside a DO Loop. The following will get a random number from 50 to 99 or -50 to -99.
'Initialize the number to be generated within the area you want excluded.
RandomNumber = 0
Do Until Abs(RandomNumber) > 49
RandomNumber = GenRndNumber (99, -99)
Be sure to declare RandomNumber and RandomLetter as appropriate. This procedure has a minor benefit for anyone who uses a lot of calls to the random number generator. It actually generates slightly less machine code than calls to the RND function. While not generally a concern nowadays, there may be times when a programmer will need to find a way to cut down on the amount of generated machine code.
Labels: numbers, random, Randomize, rnd