Table Of Contents
Randomize Statement in VBA
VBA Randomize statement is a simple one-liner statement that we add before applying the RND function. Whenever a workbook reopens, the Randomize statement provides a new seed number to the RND function depending upon the computer’s system time.
Before discussing the Randomize statement, let me introduce you to a simple RND function with VBA.
As a worksheet function “RAND,” in VBA, “RND” generates random numbers greater than 0 but less than 1.
Now, look at the syntax of the RND function.
: We can pass the argument in three ways.
- If we pass the number as <0, it generates the same random number every time.
- If we pass the number as 0, it will repeat its most recent number.
- If we pass the number >0, it keeps giving you different random numbers, i.e., the next random number in the sequence.
Example
Look at the below code.
Code:
Sub RND_Example() Debug.Print Rnd End Sub
We can see the number below when we run the code in the Immediate window.
Similarly, we can see the numbers below when we execute this code three more times.
Now, we will close the workbook and reopen it.
Now, we will go back to the visual basic editor window.
Now, the immediate window is empty and clean.
Now again, we will execute the code four times and see what the numbers we will get in the Immediate window are.
We got the same numbers as we got above.
It does not look like a random number because every time we reopen the file, we tend to get the same numbers starting from scratch.
So, how do we generate random numbers irrespective of whether the workbook reopened or not?
We need to use the “Randomize” statement.
How to Use VBA Randomize Statement?
Example #1
To get random numbers, we need to add the simple one-liner “Randomize” before the RND function.
Code:
Sub Randomize_1() Randomize Debug.Print Rnd End Sub
Now, we will run the code 4 times and see what we get.
It has generated the above numbers in my local window.
Now, we will close the file and reopen the file once again.
We usually start with a clean slate in the visual basic window.
We will again execute the code and see what numbers we get this time.
We got different numbers this time around.
Since we added the statement Randomize before the RND function, we get different random numbers every time we reopen the file.
It looks like a random number.
Example #2
Random Numbers Greater Than One
As we have seen, the “RND” function can only generate numbers from 0 to 1. But, to generate numbers greater than one random number, we need to use “RANDOM BETWEEN,” which is available with the worksheet function class.
So, to generate random numbers greater than one, we need to use the below code.
Code:
Sub Randomize_2() Randomize Debug.Print Rnd * 100 End Sub
Now, we will execute the code and see what we get.
Like this, we can use the “Randomize” statement in VBA to generate random numbers every time we reopen the Excel file.