Excel VBA: Random Number Generator with No Duplicates – 4 Examples

Enter a Code in the Visual Basic Editor

To generate random numbers with no duplicates, open Visual Basic Editor and use a VBA code. 

  • Go to Developer >> Visual Basic.

  • Select Insert >> Module.

  • Enter the code in the visual code editor and press F5 to run it.

Example 1 – Use VBA with the Rnd Function to Generate Random Numbers with No Duplicates

Generate 10 random numbers between 0 and 1 in A1:A10.

  • Enter the following code in the Visual Basic editor and press F5 to run it.
Public Sub GenerateRandomNumNoDuplicates()
    Set cellRange = Range("A1:A10")
    cellRange.Clear
    For Each Rng In cellRange
        randomNumber = Rnd
        Do While Application.WorksheetFunction.CountIf(cellRange, randomNumber) >= 1
            randomNumber = Rnd
        Loop
        Rng.Value = randomNumber
    Next
End Sub

Excel VBA Random Number Generator No Duplicates

The above image shows 10 unique random numbers between 0 and 1.

Code Breakdown

The Rnd function inserts random numbers in A1:A10.

Before inserting a new number, the Do While Loop looks for the number in A1:A10.

To check the existence of the number in the cell range, the COUNTIF function is used.

This function checks a new random number in the list before inserting it.


Example 2 – Random Number Generator with a Defined Lowerbound and Upperbound and No Duplicates

To generate random numbers within a defined range, set the lower-bound and upper-bound in the VBA code.

The lower-bound is the lowest number and the upper-bound is the highest number in the range.

  • Use the following formula in the code:

(upperbound – lowerbound + 1) * Rnd + lowerbound


2.1 Random Number Generator- Decimal

Generate 10 random numbers between 10 and 20 in A1:A10.

  •  Enter the following code in the Visual Basic editor and press F5 to run it.
Public Sub GenerateRandomNumNoDuplicates()
  lowerbound = 1
  upperbound = 10
Set cellRange = Range("A1:A10")
cellRange.Clear
For Each Rng In cellRange
    randomNumber = (upperbound - lowerbound + 1) * Rnd + lowerbound
    Do While Application.WorksheetFunction.CountIf(cellRange, randomNumber) >= 1
        randomNumber = (upperbound - lowerbound + 1) * Rnd + lowerbound
    Loop
    Rng.Value = randomNumber
    Next
End Sub

Excel VBA Random Number Generator No Duplicates

The above image shows 10 unique random numbers between 1 and 10.


2.2 Random Number Generator- Integer

Generate 20 random integer numbers between 1 and 20 in A1:B10.

  • Use the code:
Public Sub GenerateRandomNumNoDuplicates()
  lowerbound = 1
  upperbound = 20
Set cellRange = Range("A1:B10")
cellRange.Clear
For Each Rng In cellRange
    randomNumber = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
    Do While Application.WorksheetFunction.CountIf(cellRange, randomNumber) >= 1
        randomNumber = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
    Loop
    Rng.Value = randomNumber
    Next
End Sub

Excel VBA Random Number Generator No Duplicates

  • Press F5 to run it.

The above image shows 20 unique random integer numbers between 1 and 20.

Read More: How to Generate Random Number with Excel VBA


Example 3 – Specify Decimal Places in the Unique Random Number Generator in Excel VBA

Use the VBA Round function. The syntax of the function is:

Round(expression, [numdecimalplaces])

Specify the 2nd argument.

Generate 20 random numbers with 2 decimal places between 1 and 20 in A1:B10.

  • Use the code:

 

Public Sub GenerateRandomNumNoDuplicates()
  lowerbound = 1
  upperbound = 20
Set cellRange = Range("A1:B10")
cellRange.Clear
For Each Rng In cellRange
    randomNumber = Round((upperbound - lowerbound + 1) * Rnd + lowerbound, 2)
    Do While Application.WorksheetFunction.CountIf(cellRange, randomNumber) >= 1
        randomNumber = Round((upperbound - lowerbound + 1) * Rnd + lowerbound, 2)
    Loop
    Rng.Value = randomNumber
    Next
End Sub

Excel VBA Random Number Generator No Duplicates

The above image shows 20 unique random integer numbers with 2 decimal places between 1 and 20.


Example 4 – Develop a UserForm for a Random Number Generator with No Duplicates in Excel VBA

Generate 20 random numbers in A1:B10 using a UserForm with: the input values (i) lower-bound (ii) upper-bound (iii) number of decimal places.

 

  • Go to the Developer tab.
  • Click the Visual Basic option.

  • In the Visual Basic For Applications window, click Insert and select UserForm.

Click Insert and then UserForm

  • In the UserForm, add a label.
  • Name it LowerBound in Properties.

Excel VBA Random Number Generator No Duplicates

  • Add two more labels: Upperbund and DecimalPlaces.

  • Add 3 TextBoxes in the UserForm.

Excel VBA Random Number Generator No Duplicates

  • Add a CommandButton and name it Generate.

Excel VBA Random Number Generator No Duplicates

  • Double-click the CommandButton and use the following code in the code editor.
Private Sub CommandButton1_Click()
Dim lowerbound As Integer
Dim upperbound As Integer
Dim decimalPlaces As Integer
lowerbound = Val(TextBox1.Text)
upperbound = Val(TextBox2.Text)
decimalPlaces = Val(TextBox3.Text)
Set cellRange = Range("A1:B10")
cellRange.Clear
For Each Rng In cellRange
    randomNumber = Round((upperbound - lowerbound + 1) * Rnd + lowerbound, decimalPlaces)
    Do While Application.WorksheetFunction.CountIf(cellRange, randomNumber) >= 1
        randomNumber = Round((upperbound - lowerbound + 1) * Rnd + lowerbound, decimalPlaces)
    Loop
    Rng.Value = randomNumber
    Next
End Sub

Excel VBA Random Number Generator No Duplicates

  • Press F5 to run the code and display the UserForm.
  • Insert the lowerbound, upperbound, and the number of decimal places in the UserForm.
  • Click Generate.

In A1:B10, there are 20 random numbers with 2 decimal places between 1 and 30.

Excel VBA Random Number Generator No Duplicates

Read More: How to Generate Random Number in a Range with Excel VBA


Things to Remember

  • You can also use the VBA Fix function instead of the Int function to generate unique integer numbers.

Download Practice Workbook

Download the practice workbook to exercise.


Related Articles

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Al Arafat Siddique
Al Arafat Siddique

Al Arafat Siddique, BSc, Naval Architecture and Marine Engineering, Bangladesh University of Engineering and Technology, has worked on the ExcelDemy project for two years. He has written over 85+ articles for ExcelDemy. Currently, he is working as a software developer. He is leading a team of six members to develop Microsoft Office Add-ins, extending Office applications to interact with office documents. Other assigned projects to his team include creating AI-based products and online conversion tools using the latest... Read Full Bio

4 Comments
  1. Hi ,
    I would love to randomize assigned stations to a user based by theirs “station” knowledge. For exempel :
    User Stations
    Elvis : 1,5,7,9
    Andreas: 1,3,5,8,9
    Evelyn : 4,6,7,8,9 and so on .
    I am using “GenerateRandomNumNoDuplicates()” from 1-9 , but the users f.ex : Elvis can get randomized number 6 which is not in his knowledge and can not perform on that station and so on.
    Please help me out if there is possibility for that .

    • Reply Avatar photo
      Osman Goni Ridwan Aug 30, 2022 at 12:55 PM

      hello, EMIN! Actually, I haven’t understood what you asked in this comment. Can you please mail us the problem with a little more explanation at this address: [email protected].
      We will try our best to solve your problem. thank You! And, keep browsing Exceldemy.

  2. It all works but when I come out of the dev mode and open the excel on its own I cant seem to get this form up without going back into dev mode, then VBA and then F5 again?

    Could you please help

    • Hello James Ward,

      To run the code from Excel you can follow these steps:
      Developer tab >> Macros >> Select any Sub Procedure from the list

      Comment reply

      Regards
      ExcelDemy

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo