Датчик случайных чисел в excel vba

Генератор случайных чисел в 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

Получаем следующий результат:

Случайные числа, возвращаемые функцией Rnd с разными аргументами

Пример 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 при генерации случайных чисел

Строка кода 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 третьего примера:

Примеры положительных и отрицательных случайных чисел

Содержание

  1. Функция Rnd
  2. Синтаксис
  3. Возвращаемые значения
  4. Замечания
  5. Пример
  6. См. также
  7. Поддержка и обратная связь
  8. Rnd function
  9. Syntax
  10. Return values
  11. Remarks
  12. Example
  13. See also
  14. Support and feedback
  15. Оператор Randomize
  16. Синтаксис
  17. Замечания
  18. Пример
  19. См. также
  20. Поддержка и обратная связь
  21. VBA Random Number
  22. RND Function
  23. Generating a Random Number in VBA
  24. VBA Coding Made Easy
  25. VBA Code Examples Add-in
  26. VBA Random Number with Rnd and Randomize
  27. The VBA Tutorials Blog
  28. Introduction to VBA Random Numbers
  29. VBA Rnd Function
  30. VBA Randomize Statement
  31. Custom Random Number Generator Functions
  32. Rnd with Randomize
  33. Random Number between 2 Numbers
  34. Worksheet Function RANDBETWEEN
  35. VBA User-Defined Function
  36. Closing Thoughts

Функция Rnd

Возвращает значение Single , содержащее псевдослучайное число.

Синтаксис

Rnd [ (число) ]

Возвращаемые значения

Если number имеет значение Rnd создает
Меньше нуля Одно и то же число каждый раз, используя число в качестве начального значения.
Больше нуля Следующее число в псевдослучайной последовательности.
Равно нулю Самое последнее созданное число.
Не предоставлено Следующее число в псевдослучайной последовательности.

Замечания

Функция Rnd возвращает значение, меньшее 1, но большее или равное нулю.

Значение Number определяет, как Rnd создает псевдослучайное число:

Для любого данного начального значения создается одна и та же последовательность чисел, поскольку каждый последующий вызов функции Rnd использует предыдущее значение в качестве начального для следующего числа в последовательности.

Перед вызовом Rnd используйте оператор Randomize без аргумента, чтобы инициализировать генератор случайных чисел с начальным значением на основе системного таймера.

Для получения случайных целых чисел в данном диапазоне, используйте следующую формулу:

Здесь upperbound представляет собой самое большое число в диапазоне, а lowerbound — самое маленькое.

Для повтора последовательностей случайных чисел вызывайте функцию Rnd с отрицательным аргументом непосредственно перед использованием оператора Randomize с числовым аргументом. Использование randomize с тем же значением для number не повторяет предыдущую последовательность.

Пример

В этом примере используется функция Rnd для создания случайного целого значения от 1 до 6.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Rnd function

Returns a Single containing a pseudo-random number.

Syntax

Rnd [ (Number) ]

The optional Number argument is a Single or any valid numeric expression.

Return values

If Number is Rnd generates
Less than zero The same number every time, using Number as the seed.
Greater than zero The next number in the pseudo-random sequence.
Equal to zero The most recently generated number.
Not supplied The next number in the pseudo-random sequence.

The Rnd function returns a value less than 1 but greater than or equal to zero.

The value of Number determines how Rnd generates a pseudo-random number:

For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

To produce random integers in a given range, use this formula:

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for Number does not repeat the previous sequence.

Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Оператор Randomize

Инициализирует генератор случайных чисел.

Синтаксис

Рандомизация [ число ]

Необязательный аргумент number — это Variant или любое допустимое числовое выражение.

Замечания

Randomize использует число для инициализации генератора случайных чисел функции Rnd , что дает ему новое начальное значение. Если опустить число, в качестве нового начального значения используется значение, возвращаемое системным таймером.

Если оператор Randomize не используется, функция Rnd (без аргументов) использует при первом вызове число, равное начальному значению, а затем использует последнее сгенерированное число в качестве начального значения.

Для повтора последовательностей случайных чисел вызывайте функцию Rnd с отрицательным аргументом непосредственно перед использованием оператора Randomize с числовым аргументом. При использовании Randomize с тем же значением аргумента number предыдущая последовательность не повторяется.

Пример

В этом примере оператор Randomize используется для инициализации генератора случайных чисел. Поскольку аргумент number не указан, Randomize использует возвращаемое значение функции Timer в качестве нового начального значения.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Random Number

This tutorial will demonstrate how to work with random numbers in VBA.

RND Function

The RND Function generates a number that is between 0 and 1. The syntax of the RND Function is:

  • Number (Optional) – This is optional and if 0 the function returns the next generated random number. If blank the default >0, is used.

Generating a Random Number in VBA

In order to generate a random number between two values, you have to use the RND Function in combination with the INT Function (Integer Function) using the following general formula:

  • Int(lowerbound + Rnd * ( upperbound – lowerbound + 1 ) )

So, in order to generate a random number between 2 and 30, you would use the following code:

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!

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.

Источник

VBA Random Number with Rnd and Randomize

The VBA Tutorials Blog

Introduction to VBA Random Numbers

You can generate random numbers in VBA by using the Rnd function. All random number generators rely on an underlying algorithm, usually fed by what’s called a seed number. You can use the Randomize statement to create a new seed number to ensure your random numbers don’t follow a predictable pattern.

I’ll show you what I mean in this tutorial.

VBA Rnd Function

The VBA Rnd function produces a random number between 0 and 1, excluding exactly 1. Here’s a basic example:

Make powerful macros with our free VBA Developer Kit

It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.

The VBA Rnd function accepts an optional argument, like this: Rnd[Number] .

These are the things you need to keep in mind when passing numbers to the VBA Rnd function:

  • If you pass the VBA Rnd function a number less than 0, it will generate the same random number, using whatever negative value you pass it as the seed number.
  • If you pass it a 0, it will repeat the most recent random number the function gave you. In other words, each time you run it with a 0, it will give you the same number corresponding to the last answer it gave you.
  • If you omit the argument or pass the function a number greater than 0, it will simply give you a new random number — the next random number in the sequence.

I know it sounds odd to say the next random number in the sequence. It implies the the random numbers aren’t really random. Well, they aren’t.

Remember in my introduction when I said random number generators rely on an underlying algorithm fed by seed numbers? The VBA random numbers using the Rnd function are no exception. If you don’t pass the Rnd function an argument, it will produce the exact same random numbers each time you restart Excel and execute it. Don’t believe me? I’ll prove it.

Exit Excel, open it again, and run the following macro 3 times:

When I do it, it produces these results:

Now, exit Excel again, open it again and run the exact same macro 3 more times. You’ll get the same results again:

That doesn’t seem very random, does it? It’s not! Fortunately, there’s a way to make it more random by using the Randomize statement.

VBA Randomize Statement

The Randomize statement is a simple one liner that gives the Rnd function a new seed number based on your computer’s system timer. It’s really simple to use! All you have to do is type Randomize on a line in your macro, like this:

You can pass Randomize an argument, but let’s not worry about that.

Because Randomize creates a new seed number based on your computer’s system time and the system time is always changing, you have eliminated the likelihood of producing random numbers in a predictable pattern.

To prove it, run the same experiment we ran earlier, but this time include the Randomize statement in your macro.

Exit Excel, open it again, and run the following macro 3 times:

I got this result:

Now, exit Excel again, open it again and run the exact same macro 3 more times. This time, I got completely different answers:

The Randomize statement works!

Custom Random Number Generator Functions

Rnd with Randomize

If you don’t want to type Randomize each time you want a random number, you can create your own function, like this:

Copy and paste this into a module and now when you want a random number, you can just call the Random function, like this:

Random Number between 2 Numbers

Sometimes you don’t want a random number between 0 and 1. Actually, a lot of times you don’t want a random number between 0 and 1! That’s why Excel comes with a worksheet function called RANDBETWEEN. You have two choices for finding a random number between two numbers.

If available, you can either call the RANDBETWEEN function by using Application.WorksheetFunction, or you can create your own user-defined function using VBA. I’ll show you how you can do both.

Worksheet Function RANDBETWEEN

The following example creates a random integer between 0 and 10.

VBA User-Defined Function

I prefer to use my own function so I can fully take advantage of the Randomize statement. Here’s a custom function you can copy and paste into your own module to generate a random integer between two numbers

To call this custom VBA random number generator function, you would type something like:

Like the example above, this sample also produces a random integer between 0 and 10.

Closing Thoughts

That’s all I have for this VBA tutorial. Today I showed you how to generate random numbers in VBA, how to eliminate falling into the repeat random numbers trap, and I showed you how to produce random numbers between two integers using Excel VBA.

Now, go off and use these random numbers in whatever program you’re working on! I find myself using them most often in my Monte Carlo calculations.

That’s all for this tutorial. When you’re ready to take your VBA to the next level, subscribe using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

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.

Return to VBA Code Examples

This tutorial will demonstrate how to work with random numbers in VBA.

RND Function

The RND Function generates a number that is between 0 and 1. The syntax of the RND Function is:

Rnd([Number]) where:

  • Number (Optional) – This is optional and if <0, the function returns the same random number on each call using [Number] as the seed, if =0, the function returns the most recent random number, if >0 the function returns the next generated random number. If blank the default >0, is used.
Sub RndNum()
    MsgBox Rnd()
End Sub

Generating a Random Number in VBA

In order to generate a random number between two values, you have to use the RND Function in combination with the INT Function  (Integer Function) using the following general formula:

  • Int(lowerbound + Rnd * ( upperbound – lowerbound + 1 ) )

So, in order to generate a random number between 2 and 30, you would use the following code:

Sub GeneratingARandomNumber()

Dim randomNumber As Integer

randomNumber = Int(2 + Rnd * (30 - 2 + 1))
Debug.Print randomNumber

End Sub

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!
vba save as

Learn More!

vba-free-addin

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

Excel random number generator

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

Понравилась статья? Поделить с друзьями:
  • Дату следующего дня выводит формула в excel формула
  • Дату ms excel хранит как число
  • Дату excel в дату базы данных
  • Датасеты для анализа данных excel
  • Датамес excel на английском