Please Note: This article is written for users of the following Microsoft Excel versions: 97, 2000, 2002, and 2003. If you are using a later version (Excel 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Excel, click here: Determining a Random Value.
by Allen Wyatt
(last updated March 25, 2020)
VBA provides a function to return a random value. You wouldn't necessarily use this function by itself, but as part of a larger macro that may require the use of random values. The syntax for the function is as follows:
x = Rnd()
where x is the result. The value returned will always be between 0 and 1. To translate this to some other random value, all you need to do is multiply the result by the highest number you want to consider. For instance, if you wanted a random number between 1 and 25, you could use the following code line:
x = Int(25 * Rnd()) + 1
Since Rnd always returns a value between 0 and 1 (but never 1 itself), multiplying what it returns by 25 and then using the Int function on that result will return a number between 0 and 24. Finally, 1 is added to this result, so that x will be equal to a number between 1 and 25, inclusive.
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (2340) applies to Microsoft Excel 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Excel (Excel 2007 and later) here: Determining a Random Value.
Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!
Ever need to populate some cells in your worksheet with a range of data, but in random order? Here's a handy macro to get ...Discover More
Normally you use the RAND and RANDBETWEEN functions to generate random numbers. What if you want to generate random ...Discover More
It is not unusual to need to select two random items from a list. There are a couple of ways you can approach the task; ...Discover More
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.