VBA Code to generate unique random numbers based on criteria

ddub25

Well-known Member
Joined
Jan 11, 2007
Messages
617
Office Version
  1. 2019
Platform
  1. Windows
Can anyone help with adapting this code to generate random numbers in Column "L" from 1 to the total of the number of rows that meet the criteria? For example, there are 2 rows that meet the specified criteria and so random numbers 1 and 2 would be randomly generated in these rows each time I click the command button. Note that the random numbers should be unique and so the code should always generate a 1 and a 2 randomly. Thanks in advance.

Private Sub CommandButton2_Click()

Dim i As Long

For i = 5 To 28
If Range("G" & i).Value = "STR" And Range("H" & i).Value = 1 And Range("I" & i).Value = "H" And Range("K" & i).Value = "U2" Then
Range("L" & i).Value = Int((100 * Rnd) + 1)
End If
Next i

End Sub
 
Last edited:

Excel Facts

Round to nearest half hour?
Use =MROUND(A2,"0:30") to round to nearest half hour. Use =CEILING(A2,"0:30") to round to next half hour.
One way:
VBA Code:
Private Sub CommandButton2_Click()
    Dim i As Long
    Dim n As Long
    Dim rFound As Range

    For i = 5 To 28
        If Range("G" & i).Value = "STR" And Range("H" & i).Value = 1 And Range("I" & i).Value = "H" And Range("K" & i).Value = "U2" Then
            Do
                n = Application.RandBetween(1, 999)
                Set rFound = Range("L:L").Find(What:=n, LookAt:=xlWhole)
            Loop Until rFound Is Nothing
            Range("L" & i).Value = n
        End If
    Next i
End Sub
 
Upvote 0
Solution
Thanks very much rlv01, problem solved. It's much appreciated.
 
Upvote 0

Forum statistics

Threads
1,214,908
Messages
6,122,187
Members
449,071
Latest member
cdnMech

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