To generate a random number between two values in VBA, use Rnd with the formula Int((upper - lower + 1) * Rnd + lower) for integers, or lower + (upper - lower) * Rnd for decimals. For example, Int((100 - 1 + 1) * Rnd + 1) returns a whole number from 1 to 100 inclusive.
How VBA’s Rnd Function Works
VBA’s Rnd returns a single-precision floating-point number greater than or equal to 0 and less than 1. It is a pseudo-random number generator, meaning the sequence is deterministic and based on a seed value. Each call to Rnd produces the next number in the sequence, which appears random but is reproducible if you reset the seed with Randomize or by assigning a value to Rnd‘s argument.
To get a random integer within a range, you multiply Rnd by the number of possible values (upper – lower + 1), take the integer part with Int, and add the lower bound. This works because Int always rounds down to the nearest whole number, so the result is uniformly distributed across the integers in the range.
Generating Random Integers in a Range
The standard formula for a random integer between lower and upper inclusive is:
Dim lower As Long, upper As Long, result As Long
lower = 1
upper = 100
result = Int((upper - lower + 1) * Rnd + lower)
This gives each integer from lower to upper an equal chance. For example, to simulate rolling a six-sided die, use Int((6 - 1 + 1) * Rnd + 1), which yields 1 through 6. The +1 inside the parentheses is critical: without it, the maximum value would be upper - 1 because Rnd never reaches 1.
Generating Random Decimal Numbers
For a random decimal (floating-point) number between two values, use:
Dim lower As Double, upper As Double, result As Double
lower = 0.5
upper = 2.5
result = lower + (upper - lower) * Rnd
This produces a number from lower (inclusive) up to but not including upper. If you need the upper bound to be inclusive, you can use a slightly larger upper limit, but due to floating-point precision it is rarely exact. For most purposes, the exclusive upper bound is acceptable. To round to a specific number of decimal places, use Round(result, 2).
Using Randomize to Avoid Repeated Sequences
By default, VBA’s Rnd uses the same seed every time you start a new Excel session, meaning the first random number you generate will be identical across sessions. To avoid this, call Randomize before using Rnd. Randomize uses the system timer as a seed, so each run produces a different sequence.
Randomize
Dim result As Integer
result = Int((100 - 1 + 1) * Rnd + 1)
Place Randomize once at the start of your macro, not inside a loop, to avoid re-seeding repeatedly, which could cause patterns. If you need reproducible results for testing, you can pass a specific number to Randomize (e.g., Randomize 42) to get the same sequence every time.
Common Mistakes and How to Avoid Them
- Forgetting
Randomize: Without it, you get the same sequence each session, which may look random but is not. - Using
RndwithoutIntfor integers: This gives decimals, not whole numbers. Always applyIntfor integer ranges. - Off-by-one errors: The
+1inInt((upper - lower + 1) * Rnd + lower)is essential. If you omit it, the maximum isupper - 1. - Using
CIntinstead ofInt:CIntrounds to the nearest integer, which can produce values outside the range due to rounding. For example,CInt(0.5 * 10 + 1)rounds to 6, butIntgives 5. UseIntto force downward. - Re-seeding inside a loop: Calling
Randomizerepeatedly can cause the sequence to repeat or skew. Seed once.
Examples in Real Macros
Here is a complete macro that fills a selected range with random integers between 1 and 100:
Sub FillRandomIntegers()
Dim cell As Range
Dim lower As Long, upper As Long
lower = 1
upper = 100
Randomize
For Each cell In Selection
cell.Value = Int((upper - lower + 1) * Rnd + lower)
Next cell
End Sub
To generate random decimals between 0 and 1 (useful for simulations), use:
Sub FillRandomDecimals()
Dim cell As Range
Randomize
For Each cell In Selection
cell.Value = Rnd
Next cell
End Sub
Remember to save a copy of your workbook before running any macro, as macros cannot be undone with Ctrl+Z.
Frequently Asked Questions
How do I generate a random number between 1 and 10 in VBA?
Use Int((10 - 1 + 1) * Rnd + 1), which simplifies to Int(10 * Rnd + 1). This gives integers from 1 to 10 inclusive.
Why does Rnd always give the same first number?
Because VBA uses a default seed when you don’t call Randomize. The first number in the sequence is always the same. Calling Randomize before Rnd changes the seed based on the system timer, producing a different first number each time.
Can I generate a random date between two dates?
Yes. Dates in VBA are stored as numbers (the date serial). Generate a random integer between the serial values of the two dates, then convert back to a date using CDate. For example: CDate(Int((DateValue("2025-01-31") - DateValue("2025-01-01") + 1) * Rnd + DateValue("2025-01-01"))).
Is Rnd truly random?
No, it is pseudo-random. The sequence is deterministic and can be reproduced if you know the seed. For most spreadsheet tasks, this is sufficient. For cryptographic or high-stakes randomness, VBA is not suitable.
How do I generate a random number from a normal distribution?
VBA’s Rnd gives a uniform distribution. To get a normal distribution, you can use the Box-Muller transform, which combines two uniform random numbers. For example: z = Sqr(-2 * Log(Rnd)) * Cos(2 * Application.WorksheetFunction.Pi * Rnd), then scale and shift as needed.
Does Rnd work the same in Excel for Mac?
Yes, the Rnd function behaves identically in VBA on both Windows and Mac. The syntax and formulas are the same.
Related
- Google Sheets Query Unique: How to Get Distinct Values
- Generate 4 Digit Random Number in Java
- Java Code to Generate Random Number
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Copy Range to Another Sheet: Methods and TipsTo copy a range to another worksheet with Excel VBA, qualify the source and destination sheets and use…
- Add Strings to a Dictionary in VBA: Step-by-StepTo add strings to a VBA Dictionary, create a Dictionary object and call its Add method with a…
- VBA Sort Table by Column: Code and Common FixesTo sort an Excel table by one column with VBA, get the table and column by name, clear…
- Excel VBA Date to Number: Convert Dates to SerialsIn Excel VBA, convert a Date value to a number with CDbl(dateValue). The result is a serial value:…
- VBA ListBox Horizontal Scrollbar: How to Show ItTo show a horizontal scrollbar in a VBA ListBox, set the ScrollBars property to fmScrollBarsHorizontal (or fmScrollBarsBoth) in…
- Excel VBA Data Validation Drop-Down Lists: How to Build ThemTo create an Excel data-validation drop-down list with VBA, apply the xlValidateList validation type to the target cells…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.