Макрос генератор случайных чисел в excel

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

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

Случайные числа без повторов

Постановка задачи

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

  • генерация уникальных случайных кодов для товаров или пользователей
  • назначение людей на задачи (каждому по случайной из списка)
  • перестановки слов в поисковом запросе (привет seo-шникам)
  • игра в лото и т.д.

Способ 1. Простой

Для начала рассмотрим простой вариант: нам необходимо получить случайный набор из 10 целых чисел от 1 до 10. Использование встроенной в Excel функции СЛУЧМЕЖДУ (RANDBETWEEN) уникальности не гарантирует. Если ввести ее в ячейку листа и скопировать вниз на 10 ячеек, то запросто могут случиться повторы:

random-unique3.png

Поэтому мы пойдем другим путем.

Во всех версиях Excel есть функция РАНГ (RANG), предназначенная для ранжирования или, другими словами, определения топовой позиции числа в наборе. Для самого большого числа в списке ранг=1, второе в топе имеет ранг=2 и т.д.

Введем в ячейку А2 функцию СЛЧИС (RAND) без аргументов и скопируем формулу вниз на 10 ячеек. Эта функция сгенерирует нам набор из 10 случайных дробных чисел от 0 до 1:

random-unique1.png

В соседний столбец введем функцию РАНГ, чтобы определить позицию в рейтинге для каждого полученного случайного числа:

random-unique2.png

Получим в столбце В то, что хотели — любое нужное количество неповторяющихся случайных целых чисел от 1 до 10.

Чисто теоретически, может возникнуть ситуация, когда СЛЧИС выдаст нам два одинаковых случайных числа в столбце А, их ранги совпадут и мы получим повтор в столбце В. Однако, вероятность такого сценария крайне мала, учитывая тот факт, что точность составляет 15 знаков после запятой.

Способ 2. Сложный

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

Введите в ячейку А2 следующую формулу, нажмите в конце Ctrl+Shift+Enter (чтобы ввести ее как формулу массива!) и скопируйте формулу вниз на требуемое количество ячеек:

random-unique4.png

Способ 3. Макрос

Ну и, конечно, можно решить задачу с помощью программирования на Visual Basic. В одной из старых статей про случайную выборку я уже приводил  макро-функцию массива Lotto, которая выдает требуемое количество случайных неповторяющихся чисел из заданного интервала.

Ссылки по теме

  • Как подсчитать количество уникальных значений в диапазоне
  • Случайная выборка элементов из списка

excel random numberGenerating random numbers in Excel can be useful for a number of applications, from statistical sampling to computer simulation.  Even gambling.   Sometimes an unpredictable result is exactly what you need.  In Excel, there are several ways to generate random numbers depending on your requirements and skill level.  The first thing we’ll look at is the RAND function and some of its variations.  Once we have that down, we’ll write a simple macro to generate random numbers, too.  Ultimately, macros will give you the most comprehensive power, and you can learn all about their amazing capabilities in this macro and VBA tutorial.

The most common random number generator (RNG) in Excel is the RAND function.  There are two ways to enter RAND.  Because it’s such a short function, typing it manually is arguably the quickest, and a general rule of thumb is to learn the long-hand version first, thereby making you worthy of the shortcut.  The RAND syntax is: =rand().  See?  It’s practically a shortcut already.  Note: in the newer versions of Excel, as you begin to type, you will be provided with a list of relevant functions to choose from:

Screen Shot 2013-12-12 at 5.37.51 PM

You can also use the Formula Builder to insert RAND.  Even if you decide to enter RAND manually, the Formula Builder is an invaluable tool to easily and reliably attach longer, more difficult formulas.  To locate the Formula Builder, click on the Formulas tab on your Ribbon bar (the Ribbon bar is the green (Excel 2011) bar with a Home tab on its extreme left side):

Screen Shot 2013-12-12 at 7.05.16 PM

Find and click on the Formula Builder button that appears below.  This will bring up a dialogue box:

Screen Shot 2013-12-12 at 7.06.56 PM

Type in “rand” in the search bar and hit enter.  Several options should appear, but the ones in which we are most interested are RAND and RANDBETWEEN.  For now, double-click RAND.  It will be entered into the cell you preselected.  Tab over and a number between 0 and 1 will be generated in the cell; this is what RAND does, every time.  You can drag the fill handle to the range that you want to contain this formula:

Screen Shot 2013-12-12 at 7.13.35 PM

For generating numbers between 0 and numbers greater or less than 1, modify the RAND syntax in the following way: =rand()*x, in which “x” is a number of your choosing.  To generate numbers between 0 and 50, your syntax should look like this: =rand()*50.

For generating random numbers in absolutely any range of your choosing, you will use the RANDBETWEEN function.  This can be found in your formula builder, or you can quickly enter it manually: =randbetween(x,y), in which “x” is the bottom number and “y” the top number.  You’re probably getting the picture by now, but if you want to generate numbers between 35 and 75, your function should look like this: =randbetween(35,75).  And again, simply drag the fill handle over your desired range.

Now, let’s look at something a little more advanced.  First, we have to locate the macro builder.

  • Click Excel on the title bar
  • Go to Preferences
  • Under Sharing and Privacy, click Ribbon
  • There will be a list: Tab or Group Titles.  Scroll down until you see Developer and select it.

Your Ribbon bar will now display a Developer tab, and this is where you will find Macros (second from the left):

Screen Shot 2013-12-12 at 7.16.01 PM

Click on Macros to launch the Macro dialogue box.  Name your macro GenerateRandom and click Create:

Screen Shot 2013-12-12 at 5.54.41 PM

This is the code you will write (or copy/paste) into the field:

Screen Shot 2013-12-12 at 5.51.56 PM

This one is pretty self-explanatory.  Once we run the macro, we can expect random numbers between 0 and 1 to generate in rows 1-100 in column A.

So.  To run the macro, exit the Macro dialogue box.  Now all you have to do is click Macros again, select GenerateRandom from your list, and hit Run:

Screen Shot 2013-12-12 at 8.11.26 PM

Every time you run the macro, the numbers will re-generate.  You can see how useful this would be if you wanted to generate, say, ten-thousand random numbers.  You can also see how, with a few small modifications, anyone can tailor a simple piece of code to accomplish a variety of tasks.  People have written millions of macros and proudly display them online for public use.  Have some fun Googling cool Excel macros and see what you discover.  Often you can just cut and paste someone else’s hard work and instantly own an awesome, complex piece of code.  Learning to write your own macros is time well spent, but you’re likely to need more than a Google search.

Macros have you stressed?  Become a Zen Master of data (yes, they actually exist) and bridge the gap between “data” and “insight.”

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.

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

Понравилась статья? Поделить с друзьями:
  • Макрос где хранятся word
  • Макрос выполнение запроса в excel
  • Макрос выпадающий список для excel
  • Макрос выпадающий список word
  • Макрос вызвать функцию для excel