Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Playing with a Full Deck.

Playing with a Full Deck

Written by Allen Wyatt (last updated November 23, 2022)
This tip applies to Excel 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365


2

Excel is great at generating random numbers, but it is less great at filling a range of cells with random numbers in which no particular number is repeated twice. For instance, you might want to populate 52 cells with the numbers 1 through 52, in random order. (This is very similar to choosing cards from a deck in random order, where a particular card can only be chosen once. Thus, the title for this tip.)

There obviously is no built-in Excel function to provide this capability, so you are left to work with macros. Fortunately, such a macro is not terribly difficult to create. The following macro will do the trick nicely:

Sub FillRand()
    Dim nums() As Integer
    Dim maxval As Integer
    Dim nrows As Integer, ncols As Integer
    Dim j As Integer, k As Integer
    Dim Ptr As Integer
    Randomize

    Set s = Selection
    maxval = s.Cells.Count
    nrows = s.Rows.Count
    ncols = s.Columns.Count

    ReDim nums(maxval, 2)

    'Fill the initial array
    For j = 1 To maxval
        nums(j, 1) = j
        nums(j, 2) = Int((Rnd * maxval) + 1)
    Next j

    'Sort the array based on the random numbers
    For j = 1 To maxval - 1
        Ptr = j
        For k = j + 1 To maxval
            If nums(Ptr, 2) > nums(k, 2) Then Ptr = k
        Next k
        If Ptr <> j Then
            k = nums(Ptr, 1)
            nums(Ptr, 1) = nums(j, 1)
            nums(j, 1) = k
            k = nums(Ptr, 2)
            nums(Ptr, 2) = nums(j, 2)
            nums(j, 2) = k
        End If
    Next j

    'Fill in the cells
    Ptr = 0
    For j = 1 To nrows
        For k = 1 To ncols
            Ptr = Ptr + 1
            s.Cells(j, k) = nums(Ptr, 1)
        Next k
    Next j
End Sub

This macro uses a two-dimensional array (nums) to figure out which numbers to use and the order in which they should be used. Near the beginning of the macro the array is filled with a static number (1 through the number of cells) and a random number between 1 and the number of cells. This second number is then used to sort the array. Once the array is stored, it is a simple matter to place the original numbers in the cells.

By the way, the reason a two-dimensional array is used is because the Rnd function that VBA uses to generate random numbers can return duplicate values. Thus, even though the second dimension of the array can have duplicates in it, when the array is finally sorted, the first dimension will not have duplicates.

To use the macro, start by selecting the cells you want to have filled with sequential values in a random order. When you run the macro, that range is filled. For instance, if you select ten cells and then run the macro, then those cells are filled with the numbers 1 through 10, in random order.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (8269) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365. You can find a version of this tip for the older menu interface of Excel here: Playing with a Full Deck.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Determining Business Quarters from Dates

Many businesses organize information according to calendar quarters, especially when it comes to fiscal information. ...

Discover More

Formatting Text Files with VBA

Got a bunch of text that you've imported from a text file? Need to make it look better? You can take a stab at it with ...

Discover More

Setting the Left Indent of a Paragraph in a Macro

When using a macro to format text, you can set all sorts of attributes for paragraphs or individual characters. One ...

Discover More

Excel Smarts for Beginners! Featuring the friendly and trusted For Dummies style, this popular guide shows beginners how to get up and running with Excel while also helping more experienced users get comfortable with the newest features. Check out Excel 2013 For Dummies today!

More ExcelTips (ribbon)

Defining Shortcut Keys for Symbols

Do you need to use symbols frequently in your Excel data? The common way to insert them is by using the Symbol dialog ...

Discover More

Entering the Current Time

Need to enter the current time into a cell? It's easy to do using this keyboard shortcut. The shortcut is a handy one to ...

Discover More

Easily Dividing Values by 1000

Sometimes the data in a worksheet isn't in the exact format desired. If you want to divide your values by 1,000, there ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is two more than 7?

2022-11-25 01:45:13

Tomek

There is a simple non-macro solution to this problem, and it is using the same logic as proposed in the tip.
1. Create two columns with headings labelled random and unique.
2.In the first column select as many cells as you want unique numbers. Enter the formula: =RAND(). Press Ctrl+ENTER. This will populate all selected cells with this formula.
3. Fill the second column with sequential numbers from 1 to whatever is needed to have both columns of the same length.
4. (Optional but convenient) Convert the two-column range to an Excel table, which will put a filter on the columns' headings. Or just select all the data and add filter (in the Ribbon-Data Tab - select the filter button.
5. Sort the data in both columns by the first column.

You will get all numbers in the second column ordered randomly. As they are explicit numbers their order does not change unless you explicitly re-sort the table. You can copy/paste numbers from the second column elsewhere in your Workbook or use them in situ.
The first column will change every time the sheet is recalculated, which will be triggered among other things by sorting, so every time you sort the table you will get a new random order of the numbers in the second column.

Note that by using the simple RAND function (instead of RANDBETWEEN) you will get a series of 15-decimal-digit random numbers in the first column - not much chance for repetition, but as with the original solution it wouldn't matter.


2019-01-20 14:13:32

Willy Vanhaelen

Here is a much shorter macro that does the job very fasr. It is based on an idea of Rick Rothstein in the pre-2007 version of this tip:

Sub FillRand()
Dim X As Long, RandIndex As Long, Nums As Variant, Cell As Range
Randomize
Nums = Evaluate("ROW(1:" & Selection.Count & ")")
X = UBound(Nums)
For Each Cell In Selection
RandIndex = Int(X * Rnd + 1)
Cell.Value = Nums(RandIndex, 1)
Nums(RandIndex, 1) = Nums(X, 1)
X = X - 1
Next Cell
End Sub

I did a test in Excel 2007 for a whole column and it took only 16 seconds to process the more than a million cells.


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.