Генератор случайных чисел в VBA Excel. Функция Rnd, оператор Randomize, функция рабочего листа RandBetween. Синтаксис, параметры, примеры кода.
Rnd – это функция, которая возвращает значение типа Single, содержащее псевдослучайное число меньшее 1, но большее или равное нулю.
Псевдослучайное число отличается от случайного тем, что оно получено с помощью алгоритма, который, в любом случае, подчиняется какой-либо закономерности. Для решения большинства, а возможно и всех, задач в VBA Excel псевдослучайное число можно считать случайным.
Синтаксис
Rnd[(Число)]
Число – необязательный параметр, определяющий алгоритм вычисления псевдослучайного числа. Зависимость случайного числа от этого параметра:
Число | Возвращаемое значение |
---|---|
Меньше нуля | Одно и то же псевдослучайное число каждый раз, как результат использования параметра Число в качестве начального значения для алгоритма |
Больше нуля | Каждое следующее число в псевдослучайном порядке |
Равно нулю | Самое последнее псевдослучайное число, созданное функцией Rnd |
По умолчанию | Каждое следующее число в псевдослучайном порядке |
Для любого параметра Число создается одна и та же последовательность чисел, так как каждый последующий вызов функции Rnd использует предыдущее значение в качестве начального для следующего псевдослучайного числа в последовательности.
Функция Rnd – это и есть простейший генератор случайных чисел в VBA Excel, возвращающий значения в интервале 0<=Rnd<1.
Чтобы повысить «случайность» псевдослучайных чисел, возвращаемых функцией Rnd, используется оператор Randomize.
Оператор Randomize
Randomize – это оператор, который инициализирует генератор случайных чисел функции Rnd, задавая начальное число для генерации первого псевдослучайного числа.
Синтаксис
Randomize[Число]
Число – необязательный параметр, задающий начальное число для генерации. Если параметр Число опущен, используется значение, возвращенное системным таймером.
При повторном использовании в VBA Excel оператора Randomize с тем же значением аргумента Число предыдущая последовательность не повторяется.
Для повторения предыдущей последовательности случайных чисел необходимо непосредственно перед оператором Randomize с тем же значением аргумента Число вызвать функцию Rnd с отрицательным аргументом.
WorksheetFunction.RandBetween
RandBetween – функция рабочего листа, возвращающая целое случайное число в пределах заданного диапазона значений.
Синтаксис
WorksheetFunction.RandBetween(Arg1, Arg2)
- Arg1 – наименьшее целое число, которое возвращает функция рабочего листа RandBetween (обязательный параметр);
- Arg2 – наибольшее целое число, которое возвращает функция рабочего листа RandBetween (обязательный параметр).
Примеры записи строк с WorksheetFunction.RandBetween в VBA Excel (присвоение случайного числа переменной):
a = WorksheetFunction.RandBetween(—65, —15) a = WorksheetFunction.RandBetween(5, 145) |
Если данную функцию вставить в ячейку рабочего листа, например: =СЛУЧМЕЖДУ(25;55)
, случайное число будет обновляться при каждом пересчете листа.
Примеры с Rnd и Randomize
Пример 1
Запускаем генератор случайных чисел функции Rnd с разными параметрами и выводим результаты на рабочий лист Excel:
Sub Primer1() Dim i As Byte Cells(1, 1) = «Rnd(-5)» For i = 2 To 5 Cells(i, 1) = Rnd(—5) Next Cells(1, 2) = «Rnd(3)» For i = 2 To 5 Cells(i, 2) = Rnd(3) Next Cells(1, 3) = «Rnd(0)» For i = 2 To 5 Cells(i, 3) = Rnd(0) Next End Sub |
Получаем следующий результат:
Пример 2
Повторное использование оператора Randomize с тем же значением аргумента Число:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Sub Primer2() Dim i As Byte Cells(1, 1) = «Последовательность 1» Rnd (—1) Randomize 4 For i = 2 To 5 Cells(i, 1) = Rnd Next Cells(1, 2) = «Последовательность 2» Randomize 4 For i = 2 To 5 Cells(i, 2) = Rnd Next Cells(1, 3) = «Последовательность 3» Rnd (—1) Randomize 4 For i = 2 To 5 Cells(i, 3) = Rnd Next End Sub |
Строка кода Rnd (-1)
обеспечивает генерацию последовательности случайных чисел сначала при повторных использованиях оператора Randomize.
Строка кода Randomize 4
перед заполнением второго столбца не влияет на работу функции Rnd, а заполнение последовательности для третьего столбца начинается заново благодаря строке Rnd (-1)
перед оператором Randomize.
Пример 3
Создание генераторов случайных чисел для разных диапазонов. Исходим из того, что функция Rnd генерирует псевдослучайную последовательность из чисел меньше 1, но больше или равным 0.
Примеры с положительными случайными числами:
‘От 0 (включительно) до 10 10 * Rnd ‘От 6 (включительно) до 7 Rnd + 6 ‘От 5 (включительно) до 10 5 * Rnd + 5 |
Примеры с отрицательными случайными числами:
‘От -10 до 0 (включительно) —10 * Rnd ‘От -10 до 10 (включительно) —20 * Rnd + 10 ‘От -10 до -5 (включительно) —(5 * Rnd + 5) |
Пример заполнения ячеек положительными и отрицательными случайными числами на листе Excel:
Sub Primer3() Dim i As Byte Cells(1, 1) = «От 1 до 3» For i = 2 To 9 Cells(i, 1) = 2 * Rnd + 1 Next Cells(1, 2) = «От -5 до 5» For i = 2 To 9 Cells(i, 2) = —10 * Rnd + 5 Next Cells(1, 3) = «От -5 до -2» For i = 2 To 9 Cells(i, 3) = —3 * Rnd — 2 Next End Sub |
Результат выполнения кода VBA Excel третьего примера:
This Excel tutorial explains how to use the Excel RANDOMIZE function with syntax and examples.
Description
The Microsoft Excel RANDOMIZE function allows you to change the seed value used by the random number generator for the RND function.
The RANDOMIZE function is a built-in function in Excel that is categorized as a Math/Trig Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Syntax
The syntax for the RANDOMIZE function in Microsoft Excel is:
Randomize ( [ seed ] )
Parameters or Arguments
- seed
- Optional. It is a numeric seed that will be used by the RND function to generate a random number. If no seed value is provided, Excel will use the system timer as the seed value for the RND function.
Returns
The RANDOMIZE function does not return a value, but rather sets the seed value used by the RND function.
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
The Randomize function can only be used in VBA code in Microsoft Excel.
Let’s look at some Excel Randomize function examples and explore how to use the Randomize function in Excel VBA code:
For example:
'Example provided by techonthenet.com Sub Macro1 Dim LRandomNumber As Integer Randomize LRandomNumber = Int ((300 - 200 + 1) * Rnd + 200) End Sub
In this example, the variable called LRandomNumber would now contain a random number between 200 and 300. The Randomize function would ensure that the number generated is truly random by initializing the random number generator with a seed value that is equivalent to the system timer.
Warning: If you don’t call the Randomize function before calling the Rnd function, the Rnd function may return the same random number value each time. And therefore, you may not get a truly random number.
Excel VBA Randomize
To randomize the list in Excel, we must have a little large set of data from which we can select a random population. This process is also known as sampling the Randomize List in Excel. It can be done using RAND function, which creates random numbers each time when we press enter and all the created numbers are unique. RAND function generates the random number only between 0 and 1. Using RAND function along with INDEX and MATCH by which we can also generate the random numbers.
The main thing about VBA Randomize is that it does not have any syntax. We just need to use it along with RND function which has the syntax to apply.
How to Randomize a Number in Excel VBA?
Below are the different examples to Randomize a number in excel using VBA Rnd Function.
You can download this VBA Randomize Excel Template here – VBA Randomize Excel Template
Excel VBA Randomize – Example #1
It is very easy to create customize random numbers by VBA Randomize. For this, follow the below steps:
Step 1: Go to the VBA window, under the Insert menu tab select Module as shown below.
Step 2: Now write the subcategory of VBA Randomize or we can use any name to define the VBA code.
Code:
Sub VBA_Randomize() End Sub
Step 3: Now define a variable. Here, we have considered the variable RNum as data type Double. The logic behind using Double is that we will get minor changes in generated random numbers. Double will help us to see the numbers in decimals.
Code:
Sub VBA_Randomize() Dim RNum As Double End Sub
Step 4: Now assign the VBA RND function to defined variable RNum.
Code:
Sub VBA_Randomize() Dim RNum As Double RNum = Rnd End Sub
Step 5: Now to see the generation of random numbers, we will use Debug.Print which is used for printing the message.
Code:
Sub VBA_Randomize() Dim RNum As Double RNum = Rnd Debug.Print RNum End Sub
Step 6: To see the value or number generation, open the Immediate Window from the View menu list. Or we can use a short cut key as Ctrl + G to get this window.
Step 7: Now compile the code and run it by clicking on the Play button located below the menu bar. We will see the first random number in immediate window as shown below.
And if we run the code, again and again, multiple times, then we would see a few more random numbers.
Step 8: Now if we apply Randomize before RND function, then it will change the seed input which RND function was getting.
Code:
Sub VBA_Randomize() Dim RNum As Double Randomize RNum = Rnd Debug.Print RNum End Sub
Step 9: Again run the code multiple times to see what numbers are getting generated.
This is how Randomize function works in VBA if used with RND function.
Let’s see some more experiment with the same coding. We will now use CInt function with RND which is used for Data type conversion. Which means, it will convert the generated random number as Double into Integers.
Code:
Sub VBA_Randomize1() Dim RNum As Double RNum = CInt(Rnd) Debug.Print RNum End Sub
Now again run the code. We will see, now the random numbers are getting generated as Integers. But the values are in the range of 0 and 1.
We have already seen, if we keep on using the Double, then the values were coming in between 0 to 1. This is because we used Randomize along with RND function. Now let’s multiply the RND function with any number. Let’s say 20.
Code:
Sub VBA_Randomize1() Dim RNum As Double RNum = CInt(Rnd * 20) Debug.Print RNum End Sub
Now again run the code.
Now the scene is changed. The random values generated are greater than 0 but are less than 20.
Excel VBA Randomize – Example #2
There is another way to see how VBA Randomize works. We will apply some mathematical formula along with Randomize and see how to randomize helps in generating random values. But in this example, we will see the output in the message box. For this, follow the below steps:
Step 1: In a module, write the subcategory of VBA Randomize as shown below.
Code:
Sub VBA_Randomize2() End Sub
Step 2: Consider the same variable which we defined in the last example but as Integer.
Code:
Sub VBA_Randomize2() Dim RNum As Integer End Sub
Step 3: Now select the Randomize function here before we start putting mathematical formula.
Code:
Sub VBA_Randomize2() Dim RNum As Integer Randomize End Sub
Step 4: Now consider any mathematical formula such as addition, subtraction as per your requirement as shown below.
Code:
Sub VBA_Randomize2() Dim RNum As Integer Randomize RNum = Int((300 - 200 + 1) End Sub
Step 5: Now use RND function as shown below.
Code:
Sub VBA_Randomize2() Dim RNum As Integer Randomize RNum = Int((300 - 200 + 1) * Rnd + 200) End Sub
You have noticed that we have used most of the mathematical expression which is generally used.
Step 6: Now use Msgbox with a defined variable to see the generated Random numbers.
Code:
Sub VBA_Randomize2() Dim RNum As Integer Randomize RNum = Int((300 - 200 + 1) * Rnd + 200) MsgBox RNum End Sub
Step 7: Now run the code. We will get a random number as 234. This is because the number is multiplied by (300-200+1) and then added with 200. Which means that the random number is quite less in nature and because of mathematical expressions used, it is coming as 234.
And we run the code again, it will give us the message as 294.
Pros of Excel VBA Randomize
- We can generate any random number between any ranges we want.
- As the range becomes limited but still there is no limit on the generation of random numbers.
- We can limit the range of random number generation which would be greater than 0.
Things to Remember
- Randomize can be used with different functions as well. But, using this with RND function gives the result which we need.
- Randomize gives random numbers between 0 and 1 if used alone with RND.
- If we use any other number or mathematical expression with RND, then Randomize will be generated the random numbers between the highest value could be generated.
- Once done, save the file in Macro Enable excel format.
- Randomize can be used where need to generate the random numbers but between some range seed inputs.
Recommended Articles
This is a guide to VBA Randomize. Here we discuss how to Randomize a number in Excel using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Get Cell Value
- VBA Selecting Range
- VBA Variable Declaration
- VBA IsError
Home / VBA / How to Generate Random Numbers in VBA
In VBA, there are different ways that you can use to generate a random number in Excel, and in this post, we will look at all of them one by one.
RND Function
To generate a random number, in VBA, there is a function called RND. This function stands for random and when you use this function in code it returns a random number between 0 to 1. In RND, you don’t need to specify any argument.
Range("A1") = Rnd()
The above code uses it to get a random number in the A1 and it has returned 0.705547521.
But when you use it for an entire range it returns the same random number in the entire range and that makes it void for use to generate random numbers more than once.
Now here it doesn’t make sense to use it, right? But there’s a solution that you can use, FOR NEXT LOOP.
In the above code, you have a loop that loops through 10 cells (one by one) from the selected cell and adds a random number.
Here’s the full code:
Sub vba_random_number()
Dim i As Long
i = 10
For i = 1 To i
ActiveCell.Value = Rnd()
ActiveCell.Offset(1, 0).Select
Next i
End Sub
Random Number Between Two Numbers
If you want to generate a random number between two defined numbers, in that case, you need to write code by using two VBA Functions (RND + INT). The code for this formula would be like below.
Sub vba_random_number()
Dim myRnd As Integer
myRnd = Int(2 + Rnd * (45 - 10 + 1))
Range("A1") = myRnd
End Sub
When you run this macro, RND uses the max number and the min number that you have defined to generate the random number and INT removes the decimal from that.
Using Worksheet Functions in a VBA Code to Generate a Random Number
In VBA, you can access worksheet functions and use them to get a result by specifying the arguments. There are two functions from the worksheet that can help you to get a random number in the result.
- RandBetween
- RandArray
Before you use these functions make sure to understand the arguments that you need to define. Now in the below code, you have RANDBETWEEN which generates a random number between two numbers.
Range("A1") = WorksheetFunction.RandBetween(1000, 2000)
Here the max number is 2000 and the min number is 1000. In the same way, you can use the RANDARRAY which is dynamic arrays function.
Here’s the code.
Range("A1:B10") = WorksheetFunction.RandArray(10, 2, 1000, 2000, True)
If you look at the syntax of the RANDARRAY, you will find that you can enter random numbers in an entire range which is not possible with all the methods that we have discussed above.
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.
Table of contents
- Randomize Statement in VBA
- Example
- How to Use VBA Randomize Statement?
- Example #1
- Example #2
- Recommended Articles
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.
[Number]: 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 editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more 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?
You can download this VBA Randomize Excel Template here – VBA Randomize Excel Template
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.
Recommended Articles
This article has been a guide to VBA Randomize. Here, we discuss using randomized statements in VBA to generate random numbers greater than one with an example and downloadable Excel template. You can learn more about VBA from the following articles: –
- VBA ByVal
- Format Fractions in Excel
- VBA Const
- VBA Columns
We will explore the options to create your own random number generator in an Excel Worksheet or in VBA (Macro). You can generate randoms in 2 ways:
- Using Excel functions i.e. using the RAND or RANDBETWEEN functions
- Using VBA (Visual Basic macro) using the RANDOMIZE and RND functions
Random Number Generator using Excel functions
To create a random number in Excel you have 3 options:
Remember that the RAND and RANDBETWEEN functions are volatile, meaning they will be recalculated on any change to the worksheet regardless if it affects the formula. This may mean you will see constant changes to these numbers. In case it affects your performance be sure to replace your random numbers with static (copy paste as values) or generate them using VBA.
Random Numbers using VBA functions
To generate random numbers in VBA you need to use 2 functions:
- Randomize – that initializes the Rnd function with a provided seed. If you leave the argument blank it will use the actual system timer value. If you provide a certain number e.g. 10 you will always get the same sequence of random numbers. Why? Because computers use pseudo random number generators.
- Rnd – function that generates the actual random decimal numbers between 0-1.
Below a simple example:
Dim myRandom as Double Randomize 'Initialize the Rnd function myRandom = Rnd 'Generate a random number between 0-1 Debug.Print myRandom 'Print the number on console e.g. 0.308616280555725
VBA Generate whole numbers
To generate whole numbers similarly like the RANDBETWEEN Excel function we need to use the VBA CInt function to convert the decimal number to an Integer:
Dim myRandom As Double Randomize 'Initialize the Rnd function myRandom = CInt(Rnd * 100) 'Generate a random number between 0-100 Debug.Print myRandom 'e.g. 25
The above is limited to numbers starting at 0 up to the upper boundry (above 100). We can adjust the lower and upper boundries adjusting the formula above:
Dim myRandom As Double Randomize 'Initialize the Rnd function myRandom = CInt(5 + Rnd * 95) 'Generate a random number between 5-100 Debug.Print myRandom 'e.g. 5
The above will generate numbers between 5 and 100.
VBA Generate decimal numbers
Using similar approach as above and removing the VBA CInt function we can generate decimal numbers between any 2 given numbers:
Dim myRandom As Double Randomize 'Initialize the Rnd function myRandom = 5 + Rnd * 95 'Generate a random decimal number between 5-100 Debug.Print myRandom 'e.g. 5.4242442
Return to VBA Code Examples
Randomize Description
Used to change the seed value used by the random number generator for the Rnd function.
Simple Randomize Examples
Sub Randomize_Example()
Dim randomValue
Randomize
randomValue = Rnd
End Sub
Randomize Syntax
In the VBA Editor, you can type “Randomize(” to see the syntax for the Randomize statement:
The Randomize statement contains an argument:
Number: [Optional] It is a numeric “seed” that will be used by the Rnd function to generate a random number.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
(No installation required!)
Free Download