Modify Rand# Generator VBA

VinceF

Board Regular
Joined
Sep 22, 2007
Messages
199
Office Version
  1. 2016
Platform
  1. Windows
Greetings,
I have a Form control button that runs this code, it generates a random# from 1 to 18 in cells A1, A2 & A3. How can I modify the code so that it doesn't duplicate a number?

Thank You,
VinceF
Excel 2016

Sub GenerateMultipleRandomIntegers()

Dim i As Integer

For i = 1 To 3
Range("A" & i) = WorksheetFunction.RandBetween(1, 18)
Next i

End Sub
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
Here is one way:
VBA Code:
Sub GenerateMultipleRandomIntegers()

Dim i As Integer
Dim n As Integer

For i = 1 To 3
    Do
'       Calculate number
        n = WorksheetFunction.RandBetween(1, 18)
'       Check to see if number already used in range
        If Application.WorksheetFunction.CountIf(Range("A1:A3"), n) = 0 Then
'           If not duplicate, assign to cell and exit loop
            Range("A" & i) = n
            Exit Do
        End If
    Loop
Next i

End Sub
 
Upvote 0
Solution
Here is one way:
VBA Code:
Sub GenerateMultipleRandomIntegers()

Dim i As Integer
Dim n As Integer

For i = 1 To 3
    Do
'       Calculate number
        n = WorksheetFunction.RandBetween(1, 18)
'       Check to see if number already used in range
        If Application.WorksheetFunction.CountIf(Range("A1:A3"), n) = 0 Then
'           If not duplicate, assign to cell and exit loop
            Range("A" & i) = n
            Exit Do
        End If
    Loop
Next i

End Sub
 
Upvote 0
Thank you very much..!!!!! it appears to be working perfectly...

VinceF
 
Upvote 0
You are welcome.
Glad I was able to help!
 
Upvote 0

Forum statistics

Threads
1,224,833
Messages
6,181,242
Members
453,026
Latest member
cknader

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top