Written by Allen Wyatt (last updated August 7, 2021)
This tip applies to Excel 2007, 2010, 2013, 2016, 2019, and 2021
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 integer 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.
If you want a random floating point number, then simply removing the Int function from this code will not work correctly. Instead, you'll need to modify the formula in this manner:
x = (Rnd() * 24) + 1
Note:
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (9751) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and 2021. You can find a version of this tip for the older menu interface of Excel here: Determining a Random Value.
Excel Smarts for Beginners! Featuring the friendly and trusted For Dummies style, this popular guide shows beginners how to get up and running with Excel while also helping more experienced users get comfortable with the newest features. Check out Excel 2013 For Dummies today!
Normally Excel positions a UserForm in the center of your screen. You may want to position the form elsewhere, more ...
Discover MoreStrings are used quite frequently in macros. You may want to swap the contents of two string variables, and you can do so ...
Discover MoreWhen writing macros, you may want to position a message box at a specific location on the screen. This can't be done in ...
Discover MoreFREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
There are currently no comments for this tip. (Be the first to leave your comment—just use the simple form above!)
Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.
FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."
Copyright © 2025 Sharon Parq Associates, Inc.
Comments