In an earlier tutorial (More Custom Functions for Access and Excel) I included a custom function for generating random numbers within a chosen range. The function allowed the user to specify a lower limit and a higher limit, and generated a random number that fell somewhere within the range.
The function generated a whole number. But what about people who don't want a whole number? It occurred to me that with just a little more code, I could write a function that allowed the user to specify how many decimal places they required. For currency, for example, they might specify 2. It wasn't as complex as I had expected...
Public Function RandomNumbers(Lowest As Long, Highest As Long, _ Optional Decimals As Integer) Application.Volatile 'Remove this line to "freeze" the numbers If IsMissing(Decimals) Or Decimals = 0 Then Randomize RandomNumbers = Int((Highest + 1 - Lowest) * Rnd + Lowest) Else Randomize RandomNumbers = Round((Highest - Lowest) * Rnd + Lowest, Decimals) End If End Function
The function accepts 3 arguments: Lowest being the lower limit of the required range, Highest being the higher limit, and an optional one Decimals where the user can specify a number of decimal places from 0 to 9 (nine being the maximum that the random number generator can provide). Because there is a limit to the number of digits the random number generator can provide, the more digits you want on the left of the decimal point, the fewer you are given on the right. From 0-9 you can have up to 9 decimal places, from 10-999 you can have 8, from 1000-99999 you can have 7, and so on. Also, although I have declared the data type for the Highest argument as Long (the long integer data type allows numbers in the range minus 2,147,483,648 to plus 2,147,483,647 ...aren't you glad you know that?) you won't get more than 7 digits to the left of the decimal place either.
Here are some examples of the function in use in an Excel worksheet.
Example 1: Random numbers between 50 and 100 with no decimal places (whole numbers)...

Example 2: Random numbers between 50 and 100 with 2 decimal places (trailing zeros not shown so some appear to have less. The 79.9 in cell A4 is actually 79.90)...

Example 3: Random numbers between zero and 1 with 4 decimal places...

Example 4: Random numbers between 10,000 and 15,000 with 2 decimal places...

©2002 Martin Green - www.fontstuff.com - martin@fontstuff.com - All rights reserved