Random generators in excel

We have got a sequence of numbers consisting of virtually independent elements that obey a certain counting distribution. As a rule, it’s a uniform distribution.

There are different ways to generate random numbers in Excel. Let’s view the best of them.



Random Number Function In Excel

  1. The function RAND() returns a random real number of a uniform distribution. It will be less than 1, and greater than or equal to 0.
  2. The function RANDBETWEEN returns a random integer number.

Let’s view some examples of their practical application.

Selection of random numbers using RAND

This function doesn’t require arguments.

not arguments.

For example, to generate a random real number in the range 1 to 10, use the following formula: =RAND()*(5-1)+1.

range 1 to 10.

The returned random number is distributed uniformly on the interval [1,10].

Each time the sheet is calculated or the value is changed in any cell within the sheet, a new random number is returned. If you want to save the generated set of numbers, replace the formula with its value.

  1. Click on the cell containing the random number.
  2. Select the formula in the formula bar.
  3. Press F9. Then Enter.

Let us check the uniformity of distribution of the random numbers from the first selection using a distribution bar chart.

  1. We round the values that the function =RAND() returns. To do this, we use the function: =ROUND().And fill this formula with the big range: A2:A201.
  2. ROUND.

  3. Form the ranges to contain the values (bin). The first such range is 0-0.1. For the subsequent ones use the formula =B2+$B$2.
  4. bin.

  5. Determine the frequency of random numbers in range A2:A201. In cell C2 use the array formula:

    After input formula, select range C2:C11, press key F2 and press hot keys: CTRL+SHIFT+ENTER. We will execute the formula in the array Excel.

  6. in array Excel.

  7. Form the ranges with the use of the concatenation character (=»[0,0-«&C2&»]»).
  8. character.

  9. Build a distribution bar chart for the 200 values obtained with the use of the RAND() function.

distribution bar chart.

The vertical values represent the frequency. The horizontal ones represent the ranges.



RANDBETWEEN function

The syntax of the RANDBETWEEN function is as follows: (lower limit; upper limit). The first argument must be less than the second. Otherwise, the function will return an error. It is assumed that the limits are integers. The formula discards the fractional part.

An example of the function’s application:

RANDBETWEEN.

Random numbers with an accuracy of 0.1 and 0.01:

Random numbers.

How To Create Random Number Generator In Excel

Let’s create a random number generator that generates values from a certain range. Use a formula of the following form:

create a random number generator.

The formula randomly selects any of the numbers in the range A1:A10.

Let’s create a random number generator in the range 0-100, with a step of 10.

generator in the range 0-100.

It’s required to select 2 random text values from the list. Using the RAND() function, let’s match the text values in the range A1:A7 with random numbers.

RAND.

Use the =INDEX function to select two random text values from the initial list.

INDEX.

To select one random value from the list, apply the following formula:

COUNTA.

Generator Of Standard Distribution Random Numbers

The RAND and RANDBETWEEN functions return random numbers with a single distribution. There’s an equal probability for any value to fall into the lower or upper limit of the requested range. The variation of the target value turns out to be huge.

A standard distribution means most of the generated numbers are close to the target number. Let’s adjust the RANDBETWEEN formula and create an array of data with a standard distribution.

The prime cost of the X product is $100. The entire batch is subject to a standard distribution. The random variable also obeys a standard probability distribution.

Under such conditions, the average value of the range is $100. Let’s generate an array and build a chart that obeys a standard distribution with a standard deviation of $1.5.

Use the function:

NORMINV.

Excel calculates the values in the range of probabilities. As the probability of manufacturing a product with a prime cost of $100 is maximal, the formula returns values that are close to 100 more often than other values.

Let’s proceed to building the chart. First of all, you need to create a table containing the categories. To do this, split the array into periods:

  1. Determine the minimum and maximum values in the range using the =MIN(A2:102) and =MAX(A2:102) functions.
  2. Indicate the value of each period or step. In our example, it’s equal to 1.
  3. The number of categories is 10.
  4. example.

  5. The lower limit of the table containing the categories is the nearest multiple number rounded down. Enter the formula =ROUNDDOWN(C2,0) into the E1 cell.
  6. ROUNDDOWN.

  7. In the E2 cell and below, the formula will look as follows:

    That is, each subsequent value is increased by the specified step size.

  8. specified step size.

  9. Let’s calculate the number of variables in the given interval. Use the function:

    The formula will look as follows:

formula.

Based on the obtained data, we can build a chart with a normal distribution. The value axis represents the number of variables in the interval; the category axis represents the periods.

normal distribution.

A chart with a normal distribution is built. As it should be, its shape resembles a bell.

There’s a much simpler way to do the same with the help of the «Data Analysis» package. Select «Random Number Generation».

Data Analysis.

Click here to learn how to set up the standard feature: «Data Analysis».

Fill in the generation parameters. Set the distribution as «Normal».

generation parameters.

Click OK. It gives us a set of random numbers. Open the «Data Analysis» once again. Select «Histogram». Configure the parameters. Be sure to check the «Chart Output» box.

Chart Output.

The obtained result is as follows:

Download random number generators in Excel

been built.

An Excel chart with a standard distribution has been built.

Not every user will have a need for random numbers in Excel. Most people work with fixed numbers and formulas and may have no need for random numbers to appear in their reports.

However, a random number generator does have a huge use when working with different scenarios on a set of data or when performing various statistical analyses.

A financial model may use a stochastic simulation that is dependent on probabilities. The model may need to be run thousands of times, but with the random number generator providing the parameters of each simulation.

Whatever your need for random numbers, Excel has several ways to generate them.

In this post, I’ll show you all the methods you can use to insert random numbers into your workbooks.

Generate Random Numbers with the RAND function

The first way I will show you is the easiest way to generate random values in Excel.

There is a very simple RAND function that requires no parameters and will generate a random number between 0 and 1.

Syntax for the RAND Function

= RAND ( )

This function has no required or optional arguments. The function is always entered with an empty set of parenthesis.

This function will generate a decimal random number between 0 and 1, but not including 0 or 1.

Repeated values are possible but unlikely since the RAND function produces numbers from a continuous range of numbers.

The values that are returned will follow a uniform distribution. This means that any number between 0 and 1 is equally likely to be returned.

Generate Random Numbers Between Any Two Numbers

A decimal number between 0 and 1 may not be too useful if you need numbers between 1 and 10.

But you can use a simple formula involving the RAND function to generate random numbers between any two numbers.

= RAND ( ) * ( Y - X ) + X

In general, you can create a random number between X and Y by using the above formula.

= RAND ( ) * 9 + 1

For example, to generate numbers between 1 and 10 you can use the above formula.

This multiplies the random number generated by 9 and then adds 1 to it. This will produce decimal numbers between 1 and 10.

Generate Random Integer Numbers Between Any Two Numbers

Another possible need you may encounter is to generate random whole numbers between two given numbers. This can also be done using a simple formula.

= ROUND ( RAND ( ) * ( Y - X ) + X, 0 )

In general, you can use the above formula to generate random integer numbers between two values X and Y.

= ROUND ( RAND ( ) * 9 + 1, 0 )

For example, the above formula will create random integer numbers between 1 and 10.

This is the same formula as before, but using the ROUND function to round to zero decimal places.

You can copy this formula down the column on the spreadsheet, and if you keep pressing F9 to re-calculate, you will see various combinations of numbers from 1 to 10.

Since the set of possible numbers is discrete, the random numbers generated may well be duplicated in the list, depending on what the minimum and maximum are of the range.

= ROUND ( RAND ( ) * ( 4 - -3 ) + -3, 0 )

This also works for producing negative numbers. Suppose you need to generate random integer numbers between -3 and 4, then the above formula will be what you need.

Multiplying the RAND function by 7 will produce random numbers between 0 and 7. Add -3 to the result and round to zero decimal places, and this will give the range of random numbers of -3 to 4.

Generate Random Numbers using the RANDBETWEEN Function

Excel has a useful function for generating random numbers within a range of an upper and lower number.

This is easier to use than using the RAND function as it includes extra operators to arrive at your specific range.

Syntax for the RANDBETWEEN Function

= RANDBETWEEN ( bottom, top )
  • bottom is the lower range for the values to return.
  • top is the upper range for the values to return.

Both of these arguments are required.

This function will produce random integer numbers between the bottom and top values. This function will also return the upper and lower limits as possible values as it’s not strictly between in this function.

Example with the RANDBETWEEN Function

= RANDBETWEEN ( -3, 4 )

For example, if you wanted random numbers between -3 and 4, as in the previous example, you can use the above formula.

Note that the RANDBETWEEN function can only produce integer numbers. There is no way of making the function produce decimal numbers. However, it is considerably less complicated than using the RAND function with operators to achieve the same result.

Generate Random Numbers with the RANDARRAY Function

Usually, it’s the case that you don’t want just a single random value but an entire set of random values.

The RANDARRAY function is the perfect solution for this.

It will populate a range of cells with an array of random numbers, which can be very powerful.

This function is only available on the Microsoft 365 version of Excel.

Syntax for the RANDARRAY Function

= RANDARRAY ( [rows], [columns], [min], [max], [whole_number] )
  • Rows is the number of rows to return.
  • Columns is the number of columns to return.
  • Min is the minimum value for the random numbers.
  • Max is the maximum value for the random numbers.
  • Whole_Number is TRUE to return whole numbers, and FALSE to return decimal numbers.

All the arguments are optional for this function.

If no parameters are included, you will get a single random number with decimal places, in the same way as the RAND function.

Example with the RANDARRAY Function

= RANDARRAY ( 4, 3, 6, 14, TRUE )

To generate an array of 4 rows and 3 columns of whole random numbers between 6 and 14 you can use the above formula.

This will produce an array of values. Notice the blue border around the numbers? These are all produced from a single formula!

Note that the top left-hand corner of the array is always anchored on the cell that the formula is in. Pressing F9 to recalculate the spreadsheet will change all the numbers in the array.

If you do not put a minimum or maximum value, the default of 0 to 1 will be used.

The minimum value must be less than the maximum value otherwise there will be a #VALUE! error.

The array will automatically resize if you change either the rows or columns parameters in the RANDARRAY formula. This is why they’re known as dynamic arrays.

Warning: If there is already data in one of the cells in the output range that you have entered, you will get a #SPILL! error.  No data will be overwritten.

Generate Random Numbers with the Analysis Tools Add-In

There is another method that can be used to insert random numbers without using a formula.

You can use an add-in to create random numbers. Excel comes with an Analysis Tool Pak add-in, but you will need to install it before you can use it.

Install the Analysis Toolpak

Here are the steps to install the Analysis Tool Pak add-in.

  1. Click on the File tab in the ribbon.

  1. In the lower left-hand pane of the window, scroll down and click on Options. You can also use the keyboard shortcut Alt, F, T from the spreadsheet window to open the Options window.

  1. In the left-hand pane of the pop-up window, click on Add-Ins.
  2. At the bottom of the main window displayed, select Excel Add-ins from the dropdown and click on the Go button.

  1. This will display a pop-up window containing all available add-ins for Excel. Check the box for Analysis ToolPak and then click OK.

  1. On the Excel ribbon, on the Data tab, there is now an extra group called Analysis with one button called Data Analysis.

Generate Random Numbers with the Analysis Toolpak

Click on the Data Analysis button in the Analysis group.

This will display a pop-up window. Scroll down and select the Random Number Generation option and then click OK.

A new pop-up window will appear where you can enter your parameters to generate the random numbers.

There are several settings that can be customized.

  • Number of Variables This is the number of columns of random numbers that you want in your output table. If left blank, then all columns will be filled in the output range that you specify.
  • Number of Random Numbers This is the number of rows of random numbers that you want to generate. If left blank, the output range that you specify will be filled.
  • Distribution You can select several distribution methods from the drop-down such as uniform or normal distribution. Different options will become available in the Parameters section depending on your selection here.
  • Parameters Enter the values to characterize the distribution selected.
  • Random Seed This is optional and will be the starting point for the algorithm to produce the random numbers. If you use the same seed again, it will produce the same random numbers. If left blank, it will take the seed value from the timer event.
  • Output Range Enter the upper left cell of where the table is to be constructed in the spreadsheet. If you have left the Variables parameter blank, then you will need to specify an entire range. Note that existing data in that range will be overwritten.
  • New Worksheet Ply This option will insert a new worksheet within the workbook and will paste the results at Cell A1. Enter a sheet name in the adjacent box, otherwise, a default name will be used.
  • New Workbook This will create a new workbook and paste the results into cell A1 in the first sheet.

Press the OK button and Excel will insert the random number according to the selected options.

Notice that unlike the formula methods previously shown, these numbers are hardcoded and will not change when you refresh calculations in the workbook.

Generate Random Numbers with VBA

VBA (Visual Basic for Applications) is the programming language that sits behind the front end of Excel, and this can also be used to generate random numbers.

However, it is more complicated than simply entering a formula into a cell in Excel, and you do need some programming knowledge to use it.

To open the VBA editor, use the Alt + F11 keyboard shortcut.

In the left-hand pane of the window (Project Explorer), you will see the workbooks that are open (including add-ins) and the sheets available.

On the menu at the top of the window, click on Insert and then click on Module. This will add a module window to the current spreadsheet. Paste or add the following code to the module.

Sub RandomNumber()
    MsgBox Rnd()
End Sub

Press F5 to run this, and a message pop-up will appear in Excel with a random number displayed. Press OK and you will return to the code window.

Run the code again and a different random number will be displayed. The random number will be between 0 and 1, but will not include the values of 0 or 1.

You can also give the Rnd function a parameter, which is a seed for the starting point of the algorithm to produce the random numbers.

If the seed value is set to a negative number or zero, then the same random number will be displayed each time.

Using VBA functions, you can emulate all the functionality of the front-end methods that have been covered in this article.

Sub RandomNumberV2()

    MsgBox Round((Rnd() * 7) + 3)
End Sub

For example, if you wanted to generate whole random numbers between 3 and 10, then you would use the following above code.

This code multiplies the random number, by 7, and then adds 3 to it, and then rounds to zero decimal places.

Suppose that you then wanted to display your random numbers in the grid. You can do this with the following code.

Sub RandomNumberSheet()
Dim M As Integer
For M = 1 To 5
    ActiveSheet.Cells(M, 1) = Round((Rnd(10) * 7) + 3, 0)
Next M
End Sub

This code uses a For Next loop to iterate 5 times through the random number calculation and enter the results in a column of cells starting at cell A1.

Remember that any data already there will be overwritten, and there is no warning or undo feature available. Save any previous work beforehand!

Sub RandomNumberV2()
    Randomize (10)
    MsgBox Round((Rnd() * 7) + 3)
End Sub

There is also a VBA function called Randomize. You can use this before the Rnd function to reset the seed value to the timer event, or to any parameter given.

Generate Random Numbers without Duplicates or Repeats

You may well have a situation where you want to generate a range of random numbers, but you do not want to see any duplicate values appearing.

You may want to select 3 random numbers between the numbers from 1 to 10, but where each of the 3 selected numbers is unique.

You could generate random numbers with the RANDBETWEEN function and then use the Excel function Remove Duplicates from the ribbon, but this still may not give you all the numbers required.

There are several possible solutions available.

Solution with RANK.EQ and COUNTIF Functions

If you don’t have access to the RANDARRAY function in Excel, then you can use a combination of RANK.EQ and COUNTIF to get unique random numbers.

You can create your random numbers using RANDBETWEEN and then use a formula in the next column to rank them thereby giving you a randomly sorted sequence from 1 to 10.

= RANDBETWEEN ( 1, 10 )

In cell B2, enter the above formula. Copy this formula down so that there are 10 rows of random numbers going down to cell B11.

You will notice that some numbers may be duplicated and some are not shown at all.

You can then use the RANK.EQ function to rank them so as to create a sequence from 1 to 10 but that is sorted randomly.

= RANK.EQ ( B2, $B$2:$B$11 ) + COUNTIF ( $B$2:B2, B2 ) - 1

In cell C2, enter the above formula.

Note that there are absolute references used (the $ signs) so that formula references stay fixed as you copy the formula down.

Copy this formula down to cell C11, and this will display all the numbers between 1 and 10, but in random order.

To explain this formula in more depth, it uses two functions RANK.EQ and COUNTIF.

= RANK.EQ ( number, ref, [order] )
  • Number is the number that we want to find the rank of in the array.
  • Ref is the array where we want to search for the number.
  • Order is optional and allows you to find the rank in either ascending or descending order. If its omitted then ascending order is used.

The RANK.EQ function returns the rank of a number within an array of numbers.

= COUNTIF ( range, criteria )
  • Range is the range that is being searched for instances of the criteria.
  • Criteria is the value to match within the range.

The COUNTIF function counts the number of cells based on a given criterion. In this case, it is counting how many times a given random number has appeared in the list.

For each random number the RANK.EQ function will determine its ranking position relative to the other random numbers. But if the random numbers contain duplicates, then they will create a tied ranking.

The COUNTIF function will compensate for any ties in the ranking and will add one to the rank for each time the random number has previously appeared.

This creates a unique ranking where ties don’t get the same rank.

Since this rank is based on a set of random numbers the result is the same as randomizing a list of numbers from 1 to 10.

Now, if you only want 5 non-repeating numbers, you only need to take the first 5 from the ranking list.

Solution with VBA

You could also use VBA to generate a string of random numbers from 1 to 10 without duplicates.

Sub RandomNumberNoDuplicates()
Dim M As Integer, Temp As String, RandN As Integer
For M = 1 To 5
Repeat:
    RandN = Round((Rnd(10) * 9) + 1, 0)
    If InStr(Temp, RandN) Then GoTo Repeat
    ActiveSheet.Cells(M, 1) = RandN
    Temp = Temp & RandN & "|"
Next M
End Sub

This code iterates through values from 1 to 5, generating a random number between 1 and 10 each time.

It tests the random number to check if it has already been generated. This is done by concatenating successful numbers into a string and then searching that string to see if the number has already been used.

If it has been found, then it uses the label Repeat to go back and re-generate a new number. This is again tested that it has not already been used. If it is a new number, then it is added to the sheet.

Solution with Dynamic Arrays

If you have dynamic arrays in Excel, then there is a single formula method to avoid repeating values.

Suppose you want to return 5 numbers from the sequence 1 to 10. You want each number selected to be unique.

This can be done using a combination of the SEQUENCE, SORTBY, RANDARRAY, and INDEX functions.

=INDEX(
    SORTBY(
        SEQUENCE(10),
        RANDARRAY(10)
    ),
    SEQUENCE(5)
)

The above formula creates a sequence of numbers from 1 to 10.

It then sorts them in a random order using the SORTBY function and sorting on a column of random numbers generated by the RANDARRAY function. The effect is to sort the sequence in random order.

Now if you want to get 5 random and unique numbers you only need to take the first 5 numbers from the randomly sorted sequence.

This is exactly what the INDEX function does! This part of the formula will return the first 5 numbers from the randomly sorted sequence.

Conclusion

There are several ways to generate random numbers in Excel.

Whether you need whole numbers, decimals, or a range of random numbers with an upper and lower limit, the facility is available. Excel is extremely versatile on this topic.

However, bear in mind that these numbers are pseudo-random numbers generated by an algorithm.

Although the random number generator passes all the tests of randomness, they are not true random numbers.

To be a truly random number, it would have to be driven by a random event happening outside the computer environment.

For most purposes of constructing general simulations and statistical analysis, the Excel random number generator is considered fit for the purpose.

Have you used any of these methods for generating random numbers in Excel? Do you know any other methods? Let me know in the comments below!

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

There may be cases when you need to generate random numbers in Excel.

For example, to select random winners from a list or to get a random list of numbers for data analysis or to create random groups of students in class.

In this tutorial, you will learn how to generate random numbers in Excel (with and without repetitions).

Generate Random Numbers in Excel

There are two worksheet functions that are meant to generate random numbers in Excel: RAND and RANDBETWEEN.

  • RANDBETWEEN function would give you the random numbers, but there is a high possibility of repeats in the result.
  • RAND function is more likely to give you a result without repetitions. However, it only gives random numbers between 0 and 1. It can be used with RANK to generate unique random numbers in Excel (as shown later in this tutorial).

Generate Random Numbers using RANDBETWEEN function in Excel

Excel RANDBETWEEN function generates a set of integer random numbers between the two specified numbers.

RANDBETWEEN function takes two arguments – the Bottom value and the top value. It will give you an integer number between the two specified numbers only.

For example, suppose I want to generate 10 random numbers between 1 and 100.

Here are the steps to generate random numbers using RANDBETWEEN:

  • Select the cell in which you want to get the random numbers.
  • In the active cell, enter =RANDBETWEEN(1,100).
  • Hold the Control key and Press Enter.

This will instantly give me 10 random numbers in the selected cells.

Generate Random Numbers in Excel - Randbetween

While RANDBETWEEN makes it easy to get integers between the specified numbers, there is a high chance of repetition in the result.

For example, when I use the RANDBETWEEN function to get 10 random numbers and use the formula =RANDBETWEEN(1,10), it gives me a couple of duplicates.

Generate Random Numbers in Excel - Randbetween repetition

If you’re OK with duplicates, RANDBETWEEN is the easiest way to generate random numbers in Excel.

Note that RANDBETWEEN is a volatile function and recalculates every time there is a change in the worksheet. To avoid getting the random numbers recalculate, again and again, convert the result of the formula to values.

Generate Unique Random Numbers using RAND and RANK function in Excel

I tested the RAND function multiple times and didn’t find duplicate values. But as a caution, I recommend you check for duplicate values when you use this function.

Suppose I want to generate 10 random numbers in Excel (without repeats).

Here are the steps to generate random numbers in Excel without repetition:

Now you can use the values in column B as the random numbers.

Note: RAND is a volatile formula and would recalculate every time there is any change in the worksheet. Make sure you have converted all the RAND function results to values.

Caution: While I checked and didn’t find repetitions in the result of the RAND function, I still recommend you check once you have generated these numbers. You can use Conditional Formatting to highlight duplicates or use the Remove Duplicate option to get rid of it.

You May Also Like the Following Excel Tutorials:

  • Automatically Sort Data in Alphabetical Order using Formula.
  • Random Group Generator Template
  • How to Shuffle a List of Items/Names in Excel?
  • How to Do Factorial (!) in Excel (FACT function)

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 Excel for Mac 2011 Excel Starter 2010 More…Less

This article describes the formula syntax and usage of the RAND function in Microsoft Excel.

Description

RAND returns an evenly distributed random real number greater than or equal to 0 and less than 1. A new random real number is returned every time the worksheet is calculated.

Syntax

RAND()

The RAND function syntax has no arguments.

Remarks

  • To generate a random real number between a and b, use:

=RAND()*(b-a)+a

  • If you want to use RAND to generate a random number but don’t want the numbers to change every time the cell is calculated, you can enter =RAND() in the formula bar, and then press F9 to change the formula to a random number. The formula will calculate and leave you with just a value.

Example

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter. You can adjust the column widths to see all the data, if needed.

Formula

Description

Result

=RAND()

A random number greater than or equal to 0 and less than 1

varies

=RAND()*100

A random number greater than or equal to 0 and less than 100

varies

=INT(RAND()*100)

A random whole number greater than or equal to 0 and less than 100

varies

Note: When a worksheet is recalculated by entering a formula or data in a different cell, or by manually recalculating (press F9), a new random number is generated for any formula that uses the RAND function.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

See Also

Mersenne Twister algorithm

RANDBETWEEN function

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

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

  1. Генератор случайных чисел с использованием функции СЛЧИС
    • Генератор случайных чисел от нуля до заданной верхней границы диапазона
    • Генератор случайных чисел в диапазоне
    • Генератор случайных целых чисел в Excel
  2. Генератор случайных целых чисел в диапазоне с помощью функции СЛУЧМЕЖДУ
    • Создание случайных чисел с заданным количеством знаков после запятой
  3. Генератор случайных дат в Excel
  4. Генератор случайного времени в Excel
  5. Генератор случайных букв в Excel
  6. Как предотвратить повторное вычисление СЛЧИС и СЛУЧМЕЖДУ
  7. Генератор случайных чисел с помощью Анализа данных
    • Пример генерации случайных чисел с нормальным распределением

Генератор случайных чисел с использованием функции СЛЧИС

Функция СЛЧИС является одной из двух функций, специально предназначенных для генерации случайных чисел в Excel. Данная функция возвращает случайное десятичное число (действительное число) между 0 и 1.

СЛЧИС() является энергозависимой функцией, что означает, что при каждом вычислении рабочего листа создается новое случайное число. И это происходит каждый раз, когда вы выполняете какое-либо действие на листе, например, обновляете формулу (не обязательно формулу СЛЧИС, любую другую формулу на листе), редактируете ячейку или вводите новые данные.

Функция СЛЧИС доступна во всех версиях: Excel 2016, Excel 2013, Excel 2010, Excel 2007, Excel 2003.

Поскольку функция Excel СЛЧИС не имеет аргументов, вы просто вводите =СЛЧИС() в ячейке и затем копируете формулу на столько ячеек, сколько хотите:

1-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных чисел

А теперь давайте сделаем еще один шаг и напишем несколько формул СЛЧИС для генерации случайных чисел в соответствии с определенными условиями.

Генератор случайных чисел от нуля до заданной верхней границы диапазона

Чтобы сделать генератор случайных чисел от нуля до любого значения N, вы несколько раз выполняете функцию СЛЧИС с помощью N:

=СЛЧИС()*N

Например, для создания последовательности случайных чисел, больших или равных 0, но менее 50, используйте следующую формулу:

=СЛЧИС()*50

Примечание. Значение верхней границы никогда не включается в возвращаемую случайную последовательность. Например, если вы хотите получить случайные числа от 0 до 10, включая 10, правильная формула =СЛЧИС()*11.

Генератор случайных чисел в диапазоне

Чтобы создать случайное число в диапазоне, т.е. случайное число между любыми двумя указанными вами числами, используйте следующую формулу СЛЧИС:

= СЛЧИС() * (B — A) + A

Где A – это нижнее значение границы (наименьшее число), а B – верхнее значение границы (наибольшее число).

Например, чтобы сделать генератор случайных чисел от 10 до 50, вы можете использовать следующую формулу:

= СЛЧИС()*(50-10)+10

Примечание. Эта формула генерации случайных чисел никогда не вернет число, равное наибольшему числу указанного диапазона (значение B).

Генератор случайных целых чисел в Excel

Чтобы функция Excel СЛЧИС создавала случайные целые числа, возьмите одну из вышеупомянутых формул и заверните ее в функцию ЦЕЛОЕ.

Чтобы сделать генератор случайных целых чисел от 0 до 50:

= ЦЕЛОЕ(СЛЧИС()*50)

Чтобы генерировать случайные целые числа от 10 до 50:

= ЦЕЛОЕ (СЛЧИС()*(50-10)+10)

2-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных целых чисел

Генератор случайных чисел в Excel в диапазоне с помощью функции СЛУЧМЕЖДУ

СЛУЧМЕЖДУ – это еще одна функция в Excel для создания генератора случайных чисел.. Она возвращает случайные целые числа в указанном диапазоне:

СЛУЧМЕЖДУ (нижняя граница; верхняя граница)

Очевидно, что нижняя граница – это наименьшее число, а верхняя граница – наибольшее число в диапазоне случайных чисел, которые вы хотите получить.

Подобно СЛЧИС, СЛУЧМЕЖДУ в Excel является изменчивой функцией, и она также возвращает новое случайное целое число каждый раз, когда ваша таблица пересчитывается или изменяется.

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

= СЛУЧМЕЖДУ(10; 50)

3-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных чисел в заданном диапазоне

Функция СЛУЧМЕЖДУ в Excel может создавать как положительные, так и отрицательные числа случайные числа. Например, чтобы получить список случайных чисел от -10 до 10, введите следующую формулу на листе:

=СЛУЧМЕЖДУ(-10;10)

Функция СЛУЧМЕЖДУ доступна в следующих версиях: Excel 2016, Excel 2013, Excel 2010 и Excel 2007.

В более ранней версии Excel 2003, вы можете использовать формулу СЛЧИС, рассмотренную выше.

Далее в этой статье вы найдете еще несколько примеров формул, демонстрирующих, как использовать функцию СЛУЧМЕЖДУ для создания генератора случайных чисел, отличных от целых.

Создание случайных чисел с заданным количеством знаков после запятой

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

Например, чтобы получить список чисел с одним десятичным знаком, вы умножаете нижнее и верхнее значения на 10, а затем делите возвращаемое значение на 10:

= СЛУЧМЕЖДУ(нижняя граница*10; верхняя граница*10)/10

Например, чтобы получить список чисел с одним десятичным знаком, вы умножаете нижнее и верхнее значения на 10, а затем делите возвращаемое значение на 10:

Следующая формула СЛУЧМЕЖДУ возвращает случайные десятичные числа от 1 до 50:

= СЛУЧМЕЖДУ(1*10;50*10)/10

4-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных чисел с одним знаком после запятой

Аналогичным образом, чтобы сделать генератор случайных чисел от 1 до 50 с двумя знаками после запятой, вы умножаете аргументы функции СЛУЧМЕЖДУ на 100, а затем делите результат на 100:

=СЛУЧМЕЖДУ(1*100; 50*100)/100

5-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных чисел с двумя знаками после запятой

Генератор случайных дат в Excel

Чтобы вернуть список случайных дат между данными двумя датами, используйте функцию СЛУЧМЕЖДУ в сочетании с ДАТА:

=СЛУЧМЕЖДУ (ДАТА (дата начала); ДАТА (дата окончания))

Например, чтобы получить список дат между 1 сентября 2017 и 20 ноября 2017 включительно, введите следующую формулу на листе:

=СЛУЧМЕЖДУ(ДАТА(2017;9;1);ДАТА(2017;11;21))

Не забудьте применить формат даты к ячейке (ячейкам), и вы получите список случайных дат, подобных этому:

6-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных дат

Генератор случайного времени в Excel

Во внутренней системе Excel времена хранятся как десятичные числа, и вы можете использовать стандартную функцию Excel СЛЧИС для вставки случайных действительных чисел, а затем просто применить формат времени к ячейкам:

7-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайного времени функцией СЛЧИС и применение к ней формата Время

Чтобы сделать генератор случайного времени в указанном диапазоне, требуется более конкретная формула. Рассмотрим подробнее.

Генератор случайного времени в указанном диапазоне

Чтобы вставить произвольное время между любыми двумя указанными вами временными интервалами, используйте функцию ВРЕМЯ в сочетании с Excel СЛЧИС:

= ВРЕМЯ (время начала) + СЛЧИС () * (ВРЕМЯ (время начала) — ВРЕМЯ (время окончания))

Например, чтобы вставить случайное время между 5:30 и 18:00, вы можете использовать одну из следующих формул:

=ВРЕМЯ(5;30;0)+СЛЧИС()*(ВРЕМЯ(18;0;0)-ВРЕМЯ(5;0;0))

8-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайного времени в заданном интервале

Генератор случайных букв в Excel

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

=СИМВОЛ(СЛУЧМЕЖДУ(КОДСИМВ(«A»);КОДСИМВ(«Z»)))

Где A — первый символ, а Z — последний символ в диапазоне букв, которые вы хотите включить (в алфавитном порядке).

Разберем функции, в приведенной выше формуле:

  • КОДСИМВ возвращает числовые коды ANSI для указанных букв.
  • СЛУЧМЕЖДУ принимает числа, возвращаемые функциями КОДСИМВ , как нижнее и верхнее значения диапазона.
  • СИМВОЛ преобразует случайные коды ANSI, возвращаемые СЛУЧМЕЖДУ, в соответствующие буквы.

 10-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных букв

Так как коды ANSI отличаются для прописных и строчных букв, эта формула учитывает регистр.

Если кто-то наизусть знает Коды символов ANSI, ничто не мешает вам передавать коды непосредственно в функцию СЛУЧМЕЖДУ.

Например, чтобы получить произвольные прописные буквы между A (код ANSI 65) и Z (код ANSI 90), вы пишете:

=СИМВОЛ(СЛУЧМЕЖДУ (65;90))

Чтобы генерировать строчные буквы между а (код ANSI 97) в z (код ANSI 122), вы используете следующую формулу:

=СИМВОЛ(СЛУЧМЕЖДУ(97;122))

Чтобы вставить случайный специальный символ, например! «# $% & ‘() * +, -. /, используйте функцию СЛУЧМЕЖДУ с нижним параметром, установленным на 33 (код ANSI для«! »), а верхний параметр — 47 (код ANSI для« / »).

=СИМВОЛ(СЛУЧМЕЖДУ(33;47))

11-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных символов

Как предотвратить повторное вычисление СЛЧИС и СЛУЧМЕЖДУ

Если вы хотите получить постоянный набор случайных чисел, дат или текстовых строк, которые не будут меняться каждый раз, то есть зафиксировать случайные числа, когда лист пересчитывается, используйте один из следующих способов:

  1. Чтобы остановить функции СЛЧИС или СЛУЧМЕЖДУ от пересчета в одной ячейке, выберите эту ячейку, переключитесь на панель формул и нажмите F9, чтобы заменить формулу на ее значение.
  2. Чтобы предотвратить функцию случайных чисел в Excel от автоматического обновления значений в нескольких ячейках, используйте функцию Вставить. Выберите все ячейки с формулой генерации случайных значений, нажмите Ctrl+C, чтобы скопировать их, затем щелкните правой кнопкой мыши выбранный диапазон и нажмите «Вставить специальные»—> «Значения».

9-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Вставка значений

Генератор случайных чисел с помощью Анализа данных

С помощью пакета анализа данных вы, например, можете сгенерировать случайные числа нормального распределения или другого распределения. По умолчанию данный пакет не подключен, поэтому необходимо его загрузить. Как это сделать, описано в этой статье.

Пример генерации случайных чисел нормального распределения

Для того чтобы сгенерировать случайные числа нормального распределения, переходим во вкладку «ДАННЫЕ», в группе «Анализ» выбираем «Анализ данных».

12-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Анализ данных

В открывшемся списке выбираем «Генерация случайных чисел» и нажимаем кнопку «ОК».

13-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных чисел

В открывшемся окне в списке «Распределение» выбираем «Нормальное», вводим число переменных, число случайных чисел, среднее и отклонение, а также место, где вы хотите разместить сгенерированные случайные числа.

14-generator-sluchainykh-chisel-v-excel

Генератор случайных чисел в Excel – Генерация случайных чисел нормального распределения

После того, как все данные введены нажимаем кнопку «ОК», и в результате получаем сгенерированные случайные числа нормального распределения.

Ну вот на этом все. Теперь вы научились, как сделать генератор случайных чисел, чисел в диапазоне, чисел с заданным количеством знаков после запятой, случайных дат, случайного времени, а также случайных букв, а также, как сгенерировать случайные числа нормального распределения. Таким образом, владея данными знаниями, вы можете создать не только генератор случайных чисел в Excel, но и генератор паролей.

[ Генератор случайных чисел в Excel скачать ]

What Are Random Numbers In Excel?

Random numbers in Excel are used when we want to randomize our data for a sample evaluation. These numbers generated randomly. There are two built-in functions in Excel which give us random values in cells, RAND and RANDBETWEEN functions.

RAND() function provides us with any value from the range 0 to 1, whereas =RANDBETWEEN() takes input from the user for an arbitrary number range.

Randomness has many uses in science, art, statistics, cryptography, and other fields.

Generating Random numbers in excel is important because many things in real life are so complicated that they appear random. Therefore, to simulate those processes, we need random numbers.

For instance, we can generate a random number in excel using =RAND().

  • Step 1: Insert the =RAND() in cell A1.

Random Numbers in Excel - 1

  • Step 2: Press Enter.

Random Numbers in Excel - 2

Likewise, we can generate random numbers using random numbers in excel.

Table of contents
  • What Are Random Numbers In Excel?
    • How To Generate Random Numbers In Excel?
    • How To Generate Random Numbers In Excel For More Than One Cell?
    • RANDBETWEEN() Function
    • Important Things To Remember
    • Random Numbers In Excel – Project 1
    • Random Numbers In Excel – Project 2 –  Head And Tail
    • Random Numbers In Excel – Project 3 – Region Allocation
    • Random Numbers In Excel – Project 4 – Creating Ludo Dice
    • Frequently Asked Questions (FAQs)
    • Recommended Articles
  • Random Numbers in excel is used to generate numbers in excel.
  • The Random numbers in Excel function help in generating random data for sample evaluation.
  • Remember, the Random Numbers in excel is a worksheet function (WS function)
  • Excel has two built-in Random functions which yield random values. They are =RAND() function and =RANDBETWEEN().
  • The =RAND() provides us with any value from the range 0 to 1, whereas the =RANDBETWEEN() function takes input from the user for an arbitrary number range.

Random Numbers in Excel - 3

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: Random Numbers in Excel (wallstreetmojo.com)

How To Generate Random Numbers In Excel?

There are several methods to generate a random number in Excel. We will discuss the two of them: RAND() and RANDBETWEEN() functions.

You can download this Generate Random Number Excel Template here – Generate Random Number Excel Template

#1 – RAND() Function

To generate a random number in Excel between 0 and 1(excluding), we have a RAND() function in Excel.

RAND() functions return a random decimal number that is equal to or greater than 0 but less than 1 (0 ≤ random number <1). In addition, the RAND function recalculates when a worksheet is opened or changed (volatile function).

The RAND function returns the value between 0 and 1 (excluding).

random numbers

We must type =RAND() in the cell and press Enter. The value will change whenever any change is made in the sheet.

How To Generate Random Numbers In Excel For More Than One Cell?

If we want to generate random numbers in Excel for more than one cell, then we need:

  • First, select the required range, type =RAND(), and press Ctrl+Enter to give us the values.

random numbers 1

How to Stop Recalculation of Random Numbers in Excel?

As the RAND function recalculates, if any change in the sheet is made, we must copy and then paste the formulas as values if we do not want values to be changed every time. For this, we need to paste the values of the RAND() function using Paste Special so that it would no longer be a result of the “RAND ()” function. It will not be recalculated.

To do this,

  • We need to make the selection of the values.

random numbers 2

  • Press the Ctrl+C keys to copy the values.

random numbers 3

  • Without changing the selection, press the Alt+Ctrl+V keys to open the Paste Special dialog box.

random numbers 4

  • Choose Values from the options and click on OK.

random numbers 6

We can see that the value in the formula bar is the value itself, not the RAND() function. Now, these are only values.

random numbers 5

There is one more way to get the value, only not the function as a result, but that is only for one cell. If we want the value the very first time, not the function, then the steps are:

  • First, type =RAND() in the formula bar, press F9, and press the Enter key.

random numbers 7

After pressing F9, we get the value only.

random numbers 8

Value From A Different Range Other Than 0 And 1 Using RAND()

As the RAND function returns a random decimal number between 0 and 1 only, if we want the value from a different range, then we can use the following function:

Let ‘a’ be the start point.

And ‘b’ be the end point

The function would be ‘RAND()*(b-a)+a’

For example, if we have 7 as “a” and 10 as “b,” then the formula would be “=RAND()*(10-7)+7.”

random numbers 9

RANDBETWEEN() Function

As the function’s name indicates, this function returns a random integer between given integers. Like the RAND() function, this function also recalculates when a workbook is changed or opened (volatile function).

The formula of the RANDBETWEEN Function is:

RANDBETWEEN Formula

  • Bottom: An integer representing the lower value of the range.
  • Top: An integer representing the lower value of the range.

random numbers 10

To generate random numbers in Excel for the students between 0 and 100, we will use the RANDBETWEEN function.

First, we must select the data, type the formula, =RANDBETWEEN(0,100), and press the Ctrl + Enter keys. You can prefer the below-given screenshot.

random numbers 11

As values will recalculate, we can only use Alt+Ctrl+V to open the Paste Special dialog box to paste as values.

Follow the steps given below in the screenshot.

random numbers 12

Like the RAND() function, we can also type the RANDBETWEEN function in the formula bar, pressing F9 to convert the result into value, and then press the Enter key.

Important Things To Remember

  • If the bottom is greater than the top, the RANDBETWEEN function will return #NUM! Error.
  • If either of the supplied arguments is non-numeric, the function will return #VALUE! Error.
  • Both RAND() and RANDBETWEEN() functions are volatile functions (recalculates). Hence, it increases the processing time and can slow down the workbook.

Random Numbers In Excel – Project 1

We can use the RANDBETWEEN() function for getting random dates between two dates.

We will be using two dates as the bottom and top arguments.

random numbers 13

After making the selection, we need to copy down the formula using the shortcut (Ctrl+D).

random numbers 14

We can change the start date (D1) and end date (E1) to change the top and bottom values for the function.

Random Numbers In Excel – Project 2 –  Head And Tail

To randomly choose head and tail, we can use the CHOOSE function in excel with the RANDBETWEEN function.

random numbers 16

We need to copy the formula into the next and next cell every time in the game, and Head and Tail will come randomly.

random numbers 15

Random Numbers In Excel – Project 3 – Region Allocation

Many times, we have to imagine and create data for various examples. For example, suppose we have data for sales, and we need to allocate three different regions to every sale transaction.

Then, we can use the RANDBETWEEN function with the CHOOSE function.

random numbers 17

We can drag the same for the remaining cells.

random numbers 18

Random Numbers In Excel – Project 4 – Creating Ludo Dice

Using the RANDBETWEEN function, we can also create dice for Ludo. We need to use the RANDBETWEEN function in Excel VBA for the same. Please follow the below steps:

  • Merge the four cells (B2:C3) using Home Tab → Alignment Group → Merge & Center.

random numbers 19

  • Apply the border to the merged cell using the shortcut key (ALT+H+B+T) by pressing one key after another.

random numbers 20

  • Center and middle align the value using Home Tab → Alignment Group → Center and Middle Align commands.

random numbers 21

  • To create the button, use Developer tab → Controls Group → Insert Command Button

random numbers 22

  • Create the button and choose View Code from the Controls group on Developer.

random numbers 24

  • After choosing CommandButton1 from the dropdown, paste the following code:

RN = (“=RANDBETWEEN(1,6)”)

Cells(2, 2) = RN

random numbers 23

Please save the file using the .xlsm extension as we have used the VBA code in the workbook. After coming to the Excel window, deactivate the Design Mode.

random numbers 25

Now, whenever we click the button, we get a random value between 1 and 6.

random numbers 26

Frequently Asked Questions (FAQs)

1. What is Random Numbers in excel?

Random Numbers in excel is a built-in function used to generate random values. It is used when we have to calculate sample evaluation for random values.

2. What are the two functions used to generate random numbers in excel?

In excel, we can generate numbers using two functions. They are: =RAND() and =RANDBETWEEN().

The =RAND() provides us with any value from the range 0 to 1, whereas the =RANDBETWEEN() function takes input from the user for an arbitrary number range.

3. How to use RAND function in excel?

RAND() generates random numbers between 0 to 1.

For example, consider the below image where we have inserted the RAND() in a blank cell.

Random Numbers in Excel - FAQ 3

As soon as we press Enter¸ we can see that the function has generated a random number below 1 as shown in the below image.

FAQ 3 - 1

Similarly, we can generate random numbers between 0 to 1, using random numbers in excel function.

Recommended Articles

This article is a guide to Random Numbers in Excel. Here, we discuss generating random numbers in Excel using the RAND() and RANDBETWEEN functions along with multiple projects and downloadable Excel templates. You may also look at these useful functions in Excel: –

  • Randomize List in Excel
  • Auto Number in Excel
  • VBA Random Number
  • RAND Function in Excel

Working in spreadsheets

Do you need to generate a series of random numbers? Excel makes this simple and easy to do. Here’s how to create a random number generator in Excel.

Do you need to generate a list of random numbers? If so, it’s fairly easy to create a random number generator using Excel.

You can quickly generate a set of random integers between two values of your choice. You can also generate random decimal values, or even create a random list of each value from 1 to 20.

If you’re ready to get random, here’s how to create a random number generator in Excel.

How to Generate Random Numbers in Excel using RANDBETWEEN

If you want to generate random numbers in a particular range, the RANDBETWEEN function is a quick and easy way to do so. This allows you to generate random integers between any two values that you choose.

To generate random numbers in Excel using RANDBETWEEN:

  1. Click in the cell where you want your first random number to appear.
  2. Type =RANDBETWEEN(1,500) replacing ‘1’ with the lowest random number you want to generate, and ‘500’ with the highest.
    excel randbetween
  3. Press Enter and a random number in the range will be generated.
    excel random value
  4. Click and hold the small square in the bottom-right of the cell and drag downwards to fill up as many cells as you wish with the same formula.
    excel drag handle
  5. The numbers will regenerate each time you make a change in Excel. If you want to keep them the same, copy and paste your formula as values.
    excel random numbers

How to Generate Random Numbers in Excel using RAND

You can also achieve the same result by using the RAND function, although this takes a little more effort if you want to generate integers.

To generate random numbers in Excel using RAND:

  1. Click in the cell where you want your first number to appear.
  2. Type =RAND().
    excel rand
  3. Press Enter and a random decimal between 0 and 1 is generated.
    excel random decimal
  4. If you want to convert this to an integer, change your formula to =ROUND(RAND()*100,0).
    excel rand formula
  5. This will generate random numbers between 1 and 100, by multiplying the decimal by 100 and rounding it to the nearest whole number. You can change ‘100’ to whatever value you wish.
    excel random integer
  6. To create more random numbers in the same way, click and hold the small square in the bottom right-hand corner of the cell and drag it downwards.
    excel drag handle
  7. Any time a new formula is processed in Excel, the random numbers will recalculate. To keep one specific set of values, copy and paste your formula as values.
    excel random integers

How to Generate Unique Random Numbers in Excel

Due to the way that both RAND and RANDBETWEEN generate numbers, you may find that you get the same value more than once in your list of random numbers. This is to be expected; if the numbers were truly random, repeated values would be likely to occur if you generated enough values.

If you want to randomize a specific set of values, however, then it’s possible to do so. For example, you might want to put the numbers 1 to 20 into a random order.

To generate unique random numbers in Excel:

  1. Click in the cell where you want to generate your first random number.
  2. Type =RAND() and press Enter.
    excel rand
  3. Click and hold the small square in the bottom-right of the cell.
    excel drag handle
  4. Drag down to create 20 random values.
    excel 20 random decimals
  5. In the cell next to your first random value, type =RANK(B2, B$2:B$21) where ‘B’ is the column where you created your random values, ‘2’ is the row of the first value and ‘21’ is the row of the last value.
    excel rank formula
  6. Press Enter and a value between 1 and 20 will generate.
  7. Click and hold the square in the bottom-right corner of the cell and drag it down to create 20 values.
    excel drag handle
  8. Excel will create a series of random numbers between 1 and 20 in randomized order.excel rank result
  9. In the unlikely event that you get a duplicate random decimal in your first row, type = in any empty cell and press Enter. The values will regenerate.

Harness the Power of Excel

Learning how to create a random number generator in Excel is just one of the many ways that you can use Excel for far more than just storing a table of data.

For example, did you know that you can ring an alarm in Excel when certain criteria are met? You can also insert checkboxes in Excel to create useful checklists for work or home. You can also create all manner of charts, from radar charts to box plots.

Randomness is often just as necessary as order and symmetry, whether you are dealing with life or an Excel worksheet. Sometimes, you need it to ensure every value has an equal opportunity, like in a lottery.

The concept of ‘chance’ also plays an important role in simulating complex systems. It helps you test data. We often use random numbers to generate sample datasets for our tutorials too!

The good news is, Excel contains some very useful functions to help generate random numbers. The bad news is that these functions don’t always promise a unique set of random numbers.

If you look up ‘How to Generate Random Numbers without Duplicates in Excel’, you’ll probably find at least 10 different ways to do it.

Most of them work quite well too. However, we’ve noticed most tutorials leave you with a really long formula and hardly any explanation on how it works.

In this tutorial, we will show you 2 different ways in which you can generate unique random numbers in Excel using formulas.

Random Number Generating Functions in Excel

There are mainly 2 random number generating functions available in Excel. Let us see them one by one:

RANDBETWEEN Formula

The RANDBETWEEN function is a great function that helps you generate random whole numbers between an upper and lower limit.

The syntax for this function is:

=RANDBETWEEN([lower_limit],[upper_limit])

In the above formula, you can specify the lower and the upper limit. For example, if the limits are 10 and 1000, this formula will generate random numbers between these two specified limits.

This method most likely produces unique results if you have a larger range and need to generate a small number of random numbers.

For example, if you need to generate 10 numbers in the range of 10 to 1000. However, this is not the most reliable method for getting unique random numbers.

Also read: How to Generate Random Letters in Excel?

RAND Formula

The RAND function returns a decimal random number between 0 and 1. It takes no arguments, so its syntax is just

=RAND()

The great thing about this function is that there is a good probability that the numbers generated by it will not repeat, at least for 100,000 times.

The main differences between RAND() and RANDBETWEEN() are :

  • RANDBETWEEN returns a whole number while RAND returns a decimal number
  • RANDBETWEEN needs two parameters that specify the range in which the random numbers will be generated. RAND does not take any parameters. It can generate any number between 0 and 1.
  • RANDBETWEEN is less likely than RAND to generate unique random numbers.

Both RANDBETWEEN and RAND recalculate values every time the worksheet gets updated.

That means you get a new random number every time you change any cell value in the worksheet or press the F9 key.

Both these numbers fail to provide truly random numbers if used on their own, but combining them with other functions, gives a high probability of getting random numbers without repetition. Let us see how.

Using RAND and RANK to get Random Numbers in Excel Without Duplicates

You can combine the RAND and RANK functions to get a set of random numbers without duplicates.

The RANK function returns the rank of a number within a set of numbers.

Its syntax is as follows:

=RANK(number, array,[order])

The first parameter is the number or reference that you want to rank.

The second parameter is the set of numbers or range of cells that you will rank from.

The third parameter is optional. It specifies whether you want to rank in ascending or descending order. If it’s 0, the numbers are ranked in descending order. If otherwise the numbers are ranked in ascending order. By default, the numbers are ranked in descending order.

Let’s say you want 10 random numbers from A2 to A11. Here’s how you can combine the two functions:

  1. In the first cell (A2), type: =RAND(). This will generate a random number between 0 and 1.Uisng the RAND function to generate random number
  2. Pull down the fill handle (located at the bottom right corner of the cell) to copy the formula to as many cells as you need. So if you want 10 random numbers, copy it down to cell A11.Drag to gte 10 random numbers
  3. In the adjacent column (B), use the RANK formula as follows: =RANK(A2, $A$2:$A$11). The second parameter is a range of absolute cell locations. These make sure the cell references do not change when the formula is copied to other cells.
  4. Press the Return Key.
  5. Drag down the fill handle for the cell (B2) or just double click it.Unique random numbers without duplicates
  6. Now, these numbers are volatile at the moment, since the RAND() function always recalculates every time there’s a change in the worksheet. To avoid that, copy the cells (B2:B11) and paste them in the same place as value.
  7. Delete the first column (A).

This should give you a list of 10 random numbers, and that too without any repetition.

All we did here is get a random set of decimal numbers between 0 and 1 and then rank these numbers from 1 to 10 to get unique random integers.

Thus, we got a nice random set of numbers between 1 and 10 in column B (before deleting Column A).

This method should give you completely random and unique numbers with 99% assurance. But there might be slight discrepancies if you have to generate a much larger set of numbers.

For this, you can use the Remove Duplicates option to get rid of any duplicates.

Select the range of cells containing your random set of numbers.

From the Data tab, select Remove Duplicates from the Data Tools group.

Remove duplicates

Using RAND, LARGE and MATCH to get Random Numbers in Excel Without Duplicates

A similar method is to use RAND in combination with LARGE and MATCH functions. The LARGE function returns the kth largest value in a list, for example, the fourth largest value or the fifth largest value, etc. The syntax for this function is

=LARGE(array, k)

Here, the first parameter is the set of numbers or range of cells in which you want to find the largest

The second parameter is an integer that specifies the position from the largest value, i.e. the kth position.

The MATCH function looks for an item in a range of cells and then returns the relative position of that item. The syntax for this function is:

=MATCH(value, array, [match_type])

Here, the first parameter is the value you are looking for.

The second parameter is the set from which you want to find the value’s position

The third parameter is optional. It is basically used to specify the type of matching that should be done (the largest value that is less than, the smallest value that is greater than or exact match).

Let’s say you want 10 random numbers from A2 to A10. Here’s how you can combine the three functions:

  1. In the first cell (A2), type: =RAND(). This will generate a random number between 0 and 1.
  2. Pull down the fill handle (located at the bottom right corner of the cell) to copy the formula to as many cells as you need. So if you want 10 random numbers, copy it down to cell A11.
  3. In the adjacent column (B), use the LARGE formula as follows: =LARGE($A$2:$A$11,ROW(A1)). The first parameter is a range of absolute cell locations. These make sure the cell references do not change when the formula is copied to other cells. Here, we are trying to find the 1st largest value from A2 to A11. ROW(A1) means the row number of A1, in other words, the number 1. This formula could also have been written as: =LARGE($A$2:$A$11,1). But since we want the value to change when it is copied in each row, we used ROW(A1) instead.
  4. Press the Return Key
  5. Drag down the fill handle for the cell (B2) or just double click it.
  6. In the next column (C), use the MATCH function as follows: =MATCH(B2,$A$2:$A$11,0). Here, we are trying to find the position of the value in B2 in the range A2 to A11. We want an exact match, so we specify the third parameter as 0.
  7. Drag down the fill handle for the cell (C2) or just double click it.
  8. These numbers are volatile at the moment since the RAND() function always recalculates every time there’s a change in the worksheet. To avoid that, copy the cells (C2:C11) and paste them in the same place as value.
  9. Delete the first two columns (A and B).

This should give you a list of 10 random numbers without any repetition.

Generate unique random numbers using Large and Match formula

In this method, we got a random set of decimal numbers between 0 and 1 in column A and then arranged them in descending order in column B.

Next, we found the position of each number from column B in the set of random numbers of column A. This gave us a random set of numbers between 1 and 10 in column C (before deleting Columns A and B).

All we did here was convert the random decimal numbers to their integer counterparts.

In this tutorial, we showed you two ways in which you can generate random numbers in Excel without repetition.

There are plenty of other ways to do this. We leave it up to you to decide which way you find the easiest and most effective.

Other Excel tutorials you may find useful:

  • How to Reverse a Text String in Excel (Using Formula & VBA)
  • How to Highlight Every Other Row in Excel
  • How to Format Phone Numbers in Excel
  • How to Generate Random Names in Excel
  • How to Convert Decimal to Fraction in Excel
  • Excel Showing Formula Instead of Result (How to FIX!)
  • Get Unique Values from a Column in Excel

Like this post? Please share to your friends:
  • Random function in excel
  • Randbetween excel на русском
  • Rand excel по русски
  • Rand and rand in excel
  • Ran the word girls