To generate a random number in VBA, use the Rnd function, which returns a single-precision number between 0 and 1 (0 inclusive, 1 exclusive). For a random integer within a specific range, combine Rnd with arithmetic, like Int((upper - lower + 1) * Rnd + lower). Always call Randomize before using Rnd to seed the random number generator so you don’t get the same sequence each time the macro runs.
Understanding VBA’s Rnd Function
The Rnd function is VBA’s built-in random number generator. It returns a value of type Single (a floating-point number) that is greater than or equal to 0 and less than 1. For example, it might return 0.7055475, 0.1234567, or 0.9999999, but never exactly 1.0.
Here’s the simplest usage:
Sub ShowRandom()
Dim r As Single
r = Rnd() ' returns a number between 0 and 1
Debug.Print r
End Sub
The parentheses after Rnd are optional. You can write Rnd() or just Rnd. Many programmers include the parentheses for clarity.
Seeding with Randomize
Without Randomize, VBA uses the same seed value every time you start a new Excel session, which means the sequence of random numbers will be identical each time. To get different sequences, call Randomize before the first Rnd in your code. Randomize uses the system timer as the seed by default.
Sub RandomWithSeed()
Randomize ' seed the generator
Dim r As Single
r = Rnd()
Debug.Print r
End Sub
If you want a reproducible sequence (for testing), you can pass a numeric argument to Randomize, like Randomize 42. That will always produce the same sequence for the same seed.
Generating Random Integers in a Range
Most real-world tasks need a random integer between two bounds, say 1 and 10. The standard formula is:
Int((upper - lower + 1) * Rnd + lower)
For a random integer between 1 and 10:
Sub RandomInt()
Randomize
Dim lower As Integer: lower = 1
Dim upper As Integer: upper = 10
Dim result As Integer
result = Int((upper - lower + 1) * Rnd + lower)
Debug.Print result
End Sub
Why this works: Rnd returns a value in [0,1). Multiplying by (upper – lower + 1) gives a value in [0, upper-lower+1). Adding lower shifts it to [lower, upper+1). Int truncates the decimal, giving an integer from lower to upper inclusive.
Using Excel’s RANDBETWEEN Worksheet Function in VBA
You can also call Excel’s worksheet functions from VBA. WorksheetFunction.RandBetween returns a random integer between two specified bounds. This is simpler and often clearer.
Sub UseRandBetween()
Randomize
Dim lower As Long: lower = 1
Dim upper As Long: upper = 100
Dim result As Long
result = WorksheetFunction.RandBetween(lower, upper)
Debug.Print result
End Sub
Note that RandBetween is volatile—it recalculates whenever the worksheet recalculates. In VBA, it returns a new value each time you call it, regardless of calculation mode.
Choosing Between Rnd and RANDBETWEEN
Which should you use?
- Rnd is native VBA, faster, and gives you full control over the range and data type (you can get decimals).
- RANDBETWEEN is easier to read and automatically returns an integer, but it only works if you have Excel’s object library available (which you do in Excel).
- If you need a random decimal between two numbers, use
Rndwith arithmetic:lower + (upper - lower) * Rnd.
For most simple integer tasks, WorksheetFunction.RandBetween is the most straightforward. For performance-critical loops, Rnd is slightly faster because it doesn’t go through the worksheet function interface.
Common Pitfalls and How to Avoid Them
Here are frequent mistakes when generating random numbers in VBA:
- Forgetting Randomize: Without it, you get the same sequence every time you run the macro in a new session. Always call
Randomizeat the start of your procedure (or at least once before the firstRnd). - Getting 0 when you expect 1: If you use
Int(upper * Rnd) + 1for a range 1 to upper, you might get 0 ifRndreturns exactly 0. The formulaInt((upper - lower + 1) * Rnd + lower)avoids this because the +lower shifts the minimum to lower. - Using Rnd in a loop without re-seeding: If you call
Randomizeinside a loop, you might get the same number repeatedly because the timer hasn’t changed. PutRandomizebefore the loop, not inside it. - Assuming Rnd is cryptographically secure: It’s not. For security-sensitive applications (like generating passwords), use
System.Security.Cryptography.RNGCryptoServiceProvidervia .NET, but that’s beyond basic VBA.
Practical Example: Simulating a Dice Roll
Let’s put it together with a simple subroutine that simulates rolling a six-sided die ten times and writes the results to column A.
Sub RollDice()
Randomize
Dim i As Integer
Dim die As Integer
For i = 1 To 10
die = Int((6 - 1 + 1) * Rnd + 1) ' 1 to 6
Cells(i, 1).Value = die
Next i
End Sub
This writes the numbers 1 through 6 randomly to A1:A10. Each run will produce a different sequence because of Randomize.
Frequently Asked Questions
Why do I get the same random numbers every time I run my macro?
Because you haven’t called Randomize before using Rnd. Without it, VBA uses a default seed, so the sequence repeats. Add Randomize at the beginning of your procedure.
How do I generate a random number between 0 and 100 including 100?
Use Int((101) * Rnd) to get 0 to 100 inclusive, or Int((100 - 0 + 1) * Rnd + 0) which simplifies to Int(101 * Rnd). For 1 to 100, use Int(100 * Rnd) + 1.
Can I use RANDBETWEEN in VBA without typing WorksheetFunction?
Yes, you can use Application.WorksheetFunction.RandBetween or simply Application.RandBetween. In some contexts, you might need to qualify it. The safest is WorksheetFunction.RandBetween.
Is there a way to generate a random date in VBA?
Yes. Generate a random number between two date serial numbers. For example, to get a random date in 2024: Randomize then Dim d As Date: d = DateSerial(2024, 1, 1) + Int(366 * Rnd). This gives a date between Jan 1 and Dec 31, 2024.
Does Rnd produce a normal distribution?
No, Rnd produces a uniform distribution—each value between 0 and 1 is equally likely. To get a normal distribution, you’d need to apply transformations like the Box-Muller method, which is more advanced.
Can I generate random numbers in VBA without using Randomize?
Yes, but you’ll get the same sequence each time you start Excel. If that’s acceptable (e.g., for reproducible simulations), you can omit Randomize. Otherwise, always include it.
Important Safety Note
Before running any VBA macro, save a copy of your workbook. Macros cannot be undone with Ctrl+Z, and if your code writes to cells, it may overwrite existing data. Always test on a copy or a blank sheet first.
Related
- Cell Counting Equation: Hemocytometer & Alternatives
- How to Create Shortcut Keys in Windows
- Google Sheets COUNTIF Case Sensitive? Exact Match
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel Macro Recorder: Is It Good Enough for Pro Work?For Excel, the macro recorder is a built-in way to capture repeatable actions and turn them into VBA;…
- Excel VBA Loop Over an Array: Examples and PatternsTo loop over a VBA array in Excel, use For Each when you need to process every item,…
- VBA Loop Format: Syntax, Examples, and When to Use EachA VBA loop repeats a block of code while counting through values, visiting items in a collection, or…
- Sending Emails With VBA: Excel and Outlook GuideYes—Excel VBA can create and send email through classic Outlook for Windows. In Excel, add a macro that…
- VBA Functions: Basics, Examples, and How to Write ThemA VBA function is a named block of code that performs a task and returns a value. In…
- VBA Sort Oldest to Newest: Dates and MacrosTo sort dates from oldest to newest with VBA, sort the full data range by its date column…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.