+ Reply to Thread
Results 1 to 14 of 14

Need Excel to generate a random unique static number based on a specific age division

Hybrid View

  1. #1
    Registered User
    Join Date
    07-20-2019
    Location
    Utah
    MS-Off Ver
    Office 365
    Posts
    36

    Need Excel to generate a random unique static number based on a specific age division

    Hi Excel Community,

    I have a list of contestants in 6 different age divisions that I'd like Excel to automatically assign a unique random contestant number based on the age division which does not recalculate. Users won't know how to copy and paste a Randbetween output as values. So I'm looking for an alternative method to make the random number assignments static.

    Also, new contestants are added during various registration dates so as new contestants are added to the bottom of the list, they will need a random number assigned without duplicating or changing previously assigned numbers.

    Age Divisions Unique Static (Non-recalculating) Random Numbers to Assignment
    Junior Randomly assign a unique number between 101 - 199
    Intermediate Randomly assign a unique number between 201 - 299
    Senior Randomly assign a unique number between 301 - 399
    N-Jr. Randomly assign a unique number between 2 - 30*
    N-Int. Randomly assign a unique number between 31 - 65
    N-Sr. Randomly assign a unique number between 66-99
    *Bonus if you know how to make the assignment skip #13 for the superstitious contestants.

    Attached is a sample from the contest scoring workbook.

    Any help I receive is greatly appreciated.
    Attached Files Attached Files

  2. #2
    Valued Forum Contributor
    Join Date
    01-07-2022
    Location
    Europe
    MS-Off Ver
    Office 365
    Posts
    473

    Re: Need Excel to generate a random unique static number based on a specific age division

    If VBA code is ok, this could work:

    Sub assignRand()
    
    Dim lRange As Long
    Dim uRange As Long
    Dim guess As Long
    Dim NoOfTries As Long
        
    With ActiveSheet
    
        For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
        
            If .Cells(i, 4).Value = 0 Then
                
                Select Case .Cells(i, 1).Value
                
                Case "Junior"
                    lRange = 101
                    uRange = 199
                Case "Intermediate"
                    lRange = 201
                    uRange = 299
                Case "Senior"
                    lRange = 301
                    uRange = 399
                Case "N-Jr."
                    lRange = 2
                    uRange = 30
                Case "N-Int."
                    lRange = 31
                    uRange = 65
                Case "N-Sr."
                    lRange = 66
                    uRange = 99
                Case Else
                    MsgBox .Cells(i, 1).Value & " not defined"
                    Exit Sub
                End Select
                
                NoOfTries = 0
                
    reassign:
                If NoOfTries = 999 Then
                    MsgBox "Not able to assign"
                    Exit Sub
                End If
                
                guess = Int((uRange - lRange + 1) * Rnd + lRange)
                If guess = 13 Then GoTo reassign
                If WorksheetFunction.CountIf(.Range("D2:D" & i - 1), guess) = 0 Then
                    .Cells(i, 4).Value = guess
                Else
                    NoOfTries = NoOfTries + 1
                    GoTo reassign
                End If
        End If
        Next i
    
    End With
    
    End Sub
    Last edited by AskMeAboutExcel; 04-20-2022 at 01:23 AM.
    <<< If you have valued anyone's contributions in this thread, please click * to thank them for their efforts

  3. #3
    Registered User
    Join Date
    07-20-2019
    Location
    Utah
    MS-Off Ver
    Office 365
    Posts
    36

    Re: Need Excel to generate a random unique static number based on a specific age division

    Thank you, AskMeAboutExcel.

    I like the idea of using VBA because It'd be nice to turn this into a button control macro; however, I've never used VBA before, yet I'm eager to learn.

    After turning on the Developer tab, I inserted a module in the workbook and then inserted a procedure. I left the type as Sub and the scope as Public. Then I copied and pasted your code above. Since my contestant data entry starts on row 8, I changed the i = 2 statement to i = 8. Also, the age division field is column E (so the 5th column from the left) and the contestant number assignment field is column H (the 8th column). Here's how I modified your code, but I must be doing something wrong because it isn't working for me. Do you see my problem? Here's what I have:

    Public Sub assignRand()
    
    'Assign Contestant Numbers
    
    Dim lRange As Long
    Dim uRange As Long
    Dim guess As Long
    Dim NoOfTries As Long
        
    With ActiveSheet
    
        For i = 8 To Cells(Rows.Count, 1).End(xlUp).Row
        
            If .Cells(i, 8).Value = 0 Then
                
                Select Case .Cells(i, 5).Value
                
                Case "Junior"
                    lRange = 101
                    uRange = 199
                Case "Intermediate"
                    lRange = 201
                    uRange = 299
                Case "Senior"
                    lRange = 301
                    uRange = 399
                Case "N-Jr."
                    lRange = 2
                    uRange = 30
                Case "N-Int."
                    lRange = 31
                    uRange = 65
                Case "N-Sr."
                    lRange = 66
                    uRange = 99
                Case Else
                    MsgBox .Cells(i, 5).Value & " not defined"
                    Exit Sub
                End Select
                
                NoOfTries = 0
                
    reassign:
                If NoOfTries = 999 Then
                    MsgBox "Not able to assign"
                    Exit Sub
                End If
                
                guess = Int((uRange - lRange + 1) * Rnd + lRange)
                If guess = 13 Then GoTo reassign
                If WorksheetFunction.CountIf(.Range("H8:H" & i - 1), guess) = 0 Then
                    .Cells(i, 5).Value = guess
                Else
                    NoOfTries = NoOfTries + 1
                    GoTo reassign
                End If
        End If
        Next i
    
    End With
    
    End Sub
    BTW... the code you provided worked great on the little sample workbook I supplied for my original post. If I used it on the non-sample workbook, I got the "not defined" message box, which is why I thought my problem was the row and column differences. Trouble is, I don't know enough about VBA to edit the code correctly.
    Last edited by clark402; 04-23-2022 at 11:02 PM. Reason: Wrapped the code in tags to make it more readable.

  4. #4
    Valued Forum Contributor
    Join Date
    01-07-2022
    Location
    Europe
    MS-Off Ver
    Office 365
    Posts
    473

    Re: Need Excel to generate a random unique static number based on a specific age division

    Hi Clark,

    Glad that this worked for you on the sample sheet. A little challenging to debug without you're actual data, but possibly it could be this line that's the issue:

    For i = 8 To Cells(Rows.Count, 1).End(xlUp).Row
    This calculates the number of times to look through the logic, based on the number of cells with Data in Column A. If your column A is blank, then it will have an error.

    With your age divisions in column E, you can try editing this to

    For i = 8 To Cells(Rows.Count, 5).End(xlUp).Row

  5. #5
    Forum Expert
    Join Date
    07-06-2004
    Location
    Northern California
    MS-Off Ver
    2K, 2003, 2010, O365
    Posts
    1,490

    Re: Need Excel to generate a random unique static number based on a specific age division

    The most direct way to do this would be to create a table somewhere else with col A containing age division and col B 101-199 for Junior, 202-299 for Intermediate, etc, and col C containing the formula =RAND(). Sort A:C 1st on col A in ascending order, then on col C in either order. You now have a table with age divisions grouped but the distinct numbers randomly shuffled within each group. Note: age divisions will appear in alphabetical order: Intermediate, Junior, Senior. The table would be in range Ax:Cy, that is, cols A to C, rows x to y.

    Re skipping 13: don't include it in the table, so 101-112 and 114-199 for example.

    Then the kth Junior would have ID number given by
    Formula: copy to clipboard
    =IF(k<=COUNTIF(A$x:A$y,"Junior"),INDEX(A$x:C$y,MATCH("Junior",A$x:A$y,0)+k-1,2),"exhausted Junior division IDs")

    As long as you don't sort Ax:Cy again, indexing into col B will return static distinct shuffled numbers.

  6. #6
    Registered User
    Join Date
    07-20-2019
    Location
    Utah
    MS-Off Ver
    Office 365
    Posts
    36

    Re: Need Excel to generate a random unique static number based on a specific age division

    Thank you Hrlngrv. If I'm unable to make the VBA code work, I'll try your suggestion. I appreciate it.

  7. #7
    Forum Guru Bo_Ry's Avatar
    Join Date
    09-10-2018
    Location
    Thailand
    MS-Off Ver
    MS 365
    Posts
    7,222

    Re: Need Excel to generate a random unique static number based on a specific age division

    Please put this code in Sheet1

    Sub Urand()
    Dim a, l&, i&, st&, m&
    a = [LET(z,F3:G8,n,INDEX(z,,2),s,--MID(LEFT(n,FIND("-",n)-1),FIND("ween",n)+5,3),CHOOSE({1,2,3},INDEX(z,,1),s,RIGHT(n,3)-s+1))]
    l = Cells(Rows.Count, 1).End(xlUp).Row
    
    For i = 2 To l
        If Cells(i, 4) = "" Then
            st = Application.VLookup(Cells(i, 1), a, 2, 0)
            m = Application.VLookup(Cells(i, 1), a, 3, 0)
            Cells(i, 4) = Evaluate("LET(div,A2:A" & l & ",id,D2:D" & l & ",m," & m & ",l,FILTER(id,(div=""" & Cells(i, 1) & _
                """)*id,0),n,m-COUNT(l),a,SEQUENCE(m,," & st & "),SMALL(FILTER(a,ISNA(MATCH(a,l,))+(a<>13)),RANDBETWEEN(1,n)))")
        End If
    Next
    End Sub
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Column = 1 Or Target.Column = 4 Then
            Application.EnableEvents = False
            Urand
            Application.EnableEvents = True
        End If
    End Sub
    Attached Files Attached Files
    Last edited by Bo_Ry; 04-24-2022 at 05:43 AM. Reason: Add Skip 13

  8. #8
    Registered User
    Join Date
    07-20-2019
    Location
    Utah
    MS-Off Ver
    Office 365
    Posts
    36

    Re: Need Excel to generate a random unique static number based on a specific age division

    Thank you Bo_Ry. Unfortunately, there were duplicates within an age division. Every contestant needs a unique contestant number.

  9. #9
    Forum Guru Bo_Ry's Avatar
    Join Date
    09-10-2018
    Location
    Thailand
    MS-Off Ver
    MS 365
    Posts
    7,222

    Re: Need Excel to generate a random unique static number based on a specific age division

    Quote Originally Posted by clark402 View Post
    Thank you Bo_Ry. Unfortunately, there were duplicates within an age division. Every contestant needs a unique contestant number.
    Fixed

    Sub Urand()
    Dim a, l&, i&, st&, m&
    a = [LET(z,F3:G8,n,INDEX(z,,2),s,--MID(LEFT(n,FIND("-",n)-1),FIND("ween",n)+5,3),CHOOSE({1,2,3},INDEX(z,,1),s,RIGHT(n,3)-s+1))]
    l = Cells(Rows.Count, 1).End(xlUp).Row
    
    For i = 2 To l
        If Cells(i, 4) = "" Then
            st = Application.VLookup(Cells(i, 1), a, 2, 0)
            m = Application.VLookup(Cells(i, 1), a, 3, 0)
            Cells(i, 4) = Evaluate("LET(div,A2:A" & l & ",id,D2:D" & l & ",m," & m & ",l,FILTER(id,(div=""" & Cells(i, 1) & _
                """)*isnumber(id),0),a,SEQUENCE(m,," & st & "),n,m-COUNT(l)+sum(-(a=13)),SMALL(FILTER(a,ISNA(MATCH(a,l,))*(a<>13)),RANDBETWEEN(1,n)))")
        End If
    Next
    End Sub
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Column = 1 Or Target.Column = 4 Then
            Application.EnableEvents = False
            Urand
            Application.EnableEvents = True
        End If
    
    End Sub
    Attached Files Attached Files

  10. #10
    Forum Guru
    Join Date
    04-23-2012
    Location
    New Jersey, USA
    MS-Off Ver
    Excel 365
    Posts
    2,465

    Re: Need Excel to generate a random unique static number based on a specific age division

    The following Macro (Sub) and Function together will populate unique numbers in the #-Column within the ranges specified and there will be no number 13 in the list. You can set the starting row for the data (not headers) in the StartRow constant (the first Const statement), the AgeDivision column in the AgeCol constant and the output column (what you labeled #) in the NumCol constant (I assigned values that matched the data you showed us in the example workbook you posted). Copy all the code below into a general module and assign the AssignmentNumbers macro to the button you plan to put on the worksheet (the function is called by the macro, not you). Here is the code...
    Sub AssignmentNumbers()
      Dim Rw As Long, J As Long, I As Long, S As Long, NJ As Long, NI As Long, NS As Long
      Dim Jun As Variant, Inter As Variant, Sen As Variant, NJun As Variant, NInt As Variant, NSen As Variant
      Const StartRow As Long = 2
      Const AgeCol As String = "A"
      Const NumCol As String = "D"
      Jun = RandomizeArray([ROW(101:199)])
      Inter = RandomizeArray([ROW(201:299)])
      Sen = RandomizeArray([ROW(301:399)])
      NJun = RandomizeArray([SUBSTITUTE(ROW(2:29),13,30)])
      NInt = RandomizeArray([ROW(31:65)])
      NSen = RandomizeArray([ROW(66:99)])
      For Rw = StartRow To Cells(Rows.Count, AgeCol).End(xlUp).Row
        Select Case Cells(Rw, AgeCol).Value
          Case "Junior"
            J = J + 1
            Cells(Rw, NumCol) = Jun(J, 1)
          Case "Intermediate"
            I = I + 1
            Cells(Rw, NumCol) = Inter(I, 1)
          Case "Senior"
            S = S + 1
            Cells(Rw, NumCol) = Sen(S, 1)
          Case "N-Jr."
            NJ = NJ + 1
            Cells(Rw, NumCol) = NJun(NJ, 1)
          Case "N-Int."
            NI = NI + 1
            Cells(Rw, NumCol) = NInt(NI, 1)
          Case "N-Sr."
            NS = NS + 1
            Cells(Rw, NumCol) = NSen(NS, 1)
        End Select
      Next
    End Sub
    
    Function RandomizeArray(ArrayIn As Variant)
      Dim Cnt As Long, RandomIndex As Long, Tmp As Variant
      For Cnt = UBound(ArrayIn) To LBound(ArrayIn) Step -1
        RandomIndex = Application.RandBetween(LBound(ArrayIn), UBound(ArrayIn))
        Tmp = ArrayIn(RandomIndex, 1)
        ArrayIn(RandomIndex, 1) = ArrayIn(Cnt, 1)
        ArrayIn(Cnt, 1) = Tmp
      Next
      RandomizeArray = ArrayIn
    End Function
    NOTE: New random numbers will be assigned every time the button you plan to put on the worksheet is pressed, so you may want to rethink using a button to generate your numbers as it would be so easy to accidentally click it... you can press ALT+F8 and run the macro from the dialog box that appears instead. Also note that this macro is designed to run after all the AgeDivision assignments are made. If you add a new contestant or discover a mistaken age division assignment, you will have to correct those manually if the number assignments have already been given out to the contestants (remember, running the macro randomizes all assignments).
    Last edited by Rick Rothstein; 04-24-2022 at 05:03 AM.

  11. #11
    Registered User
    Join Date
    07-20-2019
    Location
    Utah
    MS-Off Ver
    Office 365
    Posts
    36

    Re: Need Excel to generate a random unique static number based on a specific age division

    Thank you, Rick. I'm glad you put the note at the bottom of your post. Is there a way to modify your code so that if there is a value already assigned, it will skip it instead of changing it. That way when new contestants are added to the bottom of the list throughout the competition year, it will assign the new numbers only to the blank unassigned fields without duplicating previously assigned numbers.

    The code AskMeAboutExcel provided above functioned great in the sample workbook in my original post. Unfortunately, when I tried to use it in my real workbook, I got the message box "not defined". Since that message box is written into the code it tells me the code is working correctly, but I believe the problem is due to the differences in rows and columns between the two workbooks. In my original post with the sample workbook, the data started in cell A1. In my real workbook, the data starts in cell E8 with the header row in row 7. The age divisions are in column E, column F is the contestant's first name, column G is the last name, and column H is the contestant number that I'm trying to populate with a static, nonduplicated, random contestant number, dependent on the age division.

    I don't know enough about VBA to modify AskMeAboutExcel's code to adjust the rows and column references so it will work right in my real workbook.

  12. #12
    Forum Guru
    Join Date
    04-23-2012
    Location
    New Jersey, USA
    MS-Off Ver
    Excel 365
    Posts
    2,465

    Re: Need Excel to generate a random unique static number based on a specific age division

    Quote Originally Posted by clark402 View Post
    Is there a way to modify your code so that if there is a value already assigned, it will skip it instead of changing it.
    Replace both the macro and function I gave you earlier with these...
    Sub AssignmentNumbers()
      Dim Rw As Long, LastRow As Long, J As Long, I As Long, S As Long, NJ As Long, NI As Long, NS As Long
      Dim Jun As Variant, Inter As Variant, Sen As Variant, NJun As Variant, NInt As Variant, NSen As Variant
      Const StartRow As Long = 2
      Const AgeCol As String = "A"
      Const NumCol As String = "D"
      Jun = RandomizeArray([TRANSPOSE(ROW(101:199))])
      Inter = RandomizeArray([TRANSPOSE(ROW(201:299))])
      Sen = RandomizeArray([TRANSPOSE(ROW(301:399))])
      NJun = RandomizeArray([TRANSPOSE(SUBSTITUTE(ROW(2:29),13,30))])
      NInt = RandomizeArray([TRANSPOSE(ROW(31:65))])
      NSen = RandomizeArray([TRANSPOSE(ROW(66:99))])
      LastRow = Cells(Rows.Count, AgeCol).End(xlUp).Row
      For Rw = StartRow To LastRow
        If Cells(Rw, NumCol) <> "" Then
          Select Case Cells(Rw, AgeCol).Value
            Case "Junior"
              Jun = Filter(Jun, Cells(Rw, NumCol), False)
            Case "Intermediate"
              Inter = Filter(Inter, Cells(Rw, NumCol), False)
            Case "Senior"
              Sen = Filter(Sen, Cells(Rw, NumCol), False)
            Case "N-Jr."
              NJun = Filter(NJun, Cells(Rw, NumCol), False)
            Case "N-Int."
              NInt = Filter(NInt, Cells(Rw, NumCol), False)
            Case "N-Sr."
              NSen = Filter(NSen, Cells(Rw, NumCol), False)
          End Select
        End If
      Next
      For Rw = StartRow To LastRow
        If Cells(Rw, NumCol) = "" Then
          Select Case Cells(Rw, AgeCol).Value
            Case "Junior"
              J = J + 1
              Cells(Rw, NumCol) = Jun(J)
            Case "Intermediate"
              I = I + 1
              Cells(Rw, NumCol) = Inter(I)
            Case "Senior"
              S = S + 1
              Cells(Rw, NumCol) = Sen(S)
            Case "N-Jr."
              NJ = NJ + 1
              Cells(Rw, NumCol) = NJun(NJ)
            Case "N-Int."
              NI = NI + 1
              Cells(Rw, NumCol) = NInt(NI)
            Case "N-Sr."
              NS = NS + 1
              Cells(Rw, NumCol) = NSen(NS)
          End Select
        End If
      Next
    End Sub
    
    Function RandomizeArray(ArrayIn As Variant)
      Dim Cnt As Long, RandomIndex As Long, Tmp As Variant
      For Cnt = UBound(ArrayIn) To LBound(ArrayIn) Step -1
        RandomIndex = Application.RandBetween(LBound(ArrayIn), UBound(ArrayIn))
        Tmp = ArrayIn(RandomIndex)
        ArrayIn(RandomIndex) = ArrayIn(Cnt)
        ArrayIn(Cnt) = Tmp
      Next
      RandomizeArray = ArrayIn
    End Function
    Note: If you change the age division of any cells, you must manually delete the assigned number in the NumCol so that it becomes blank... my new code will only assign a number to a cell that is blank (if there is an existing number, it will remain unchanged).

  13. #13
    Registered User
    Join Date
    07-20-2019
    Location
    Utah
    MS-Off Ver
    Office 365
    Posts
    36

    Re: Need Excel to generate a random unique static number based on a specific age division

    This code appears to be working. I'm marking this thread as solved.

    Huge thank you to everyone that helped me. And a special thank you to AskMeAboutExcel for giving me the code that met my numerous requirements and for helping me to successfully modify it. Your explanation that the line of code was counting columns was one tiny bit of a large sum of knowledge I lack, but it was the key to me being able to modify it successfully.

    I'm pretty excited to assign this macro to a button for the future users of the workbook. This is my first time working with VBA and I'm very happy now instead of frustrated.

    Public Sub assignRand()
    
    'Assign Contestant Numbers
    
    Dim lRange As Long
    Dim uRange As Long
    Dim guess As Long
    Dim NoOfTries As Long
        
    With ActiveSheet
    
        For i = 8 To Cells(Rows.Count, 5).End(xlUp).Row
        
            If .Cells(i, 8).Value = 0 Then
                
                Select Case .Cells(i, 5).Value
                
                Case "Junior"
                    lRange = 101
                    uRange = 199
                Case "Intermediate"
                    lRange = 201
                    uRange = 299
                Case "Senior"
                    lRange = 301
                    uRange = 399
                Case "N-Jr."
                    lRange = 2
                    uRange = 30
                Case "N-Int."
                    lRange = 31
                    uRange = 65
                Case "N-Sr."
                    lRange = 66
                    uRange = 99
                Case Else
                    MsgBox .Cells(i, 5).Value & " not defined"
                    Exit Sub
                End Select
                
                NoOfTries = 0
                
    reassign:
                If NoOfTries = 999 Then
                    MsgBox "Not able to assign"
                    Exit Sub
                End If
                
                guess = Int((uRange - lRange + 1) * Rnd + lRange)
                If guess = 13 Then GoTo reassign
                If WorksheetFunction.CountIf(.Range("H8:H" & i - 1), guess) = 0 Then
                    .Cells(i, 8).Value = guess
                Else
                    NoOfTries = NoOfTries + 1
                    GoTo reassign
                End If
        End If
        Next i
    
    End With
    
    End Sub

  14. #14
    Forum Guru
    Join Date
    04-23-2012
    Location
    New Jersey, USA
    MS-Off Ver
    Excel 365
    Posts
    2,465

    Re: Need Excel to generate a random unique static number based on a specific age division

    If you plan to use the code you posted, you will need to add a Randomize statement to it (by the way, you have two other code solutions that do not require this); otherwise, when you close the workbook and then reopen it at a later date, your code will generate the same exact "random numbers" as it did the first time you used your code. To do this, just put the word Randomize on a line all by itself near the beginning of your code (after the last Dim statement would work).

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 3
    Last Post: 06-16-2019, 12:04 PM
  2. [SOLVED] Generate random values between two number and specific string
    By YasserKhalil in forum Excel Programming / VBA / Macros
    Replies: 10
    Last Post: 12-28-2016, 04:15 PM
  3. [SOLVED] Generate static random numbers within formula
    By SteveTheFish in forum Excel Formulas & Functions
    Replies: 10
    Last Post: 04-10-2015, 02:51 AM
  4. Replies: 5
    Last Post: 06-21-2013, 10:40 AM
  5. [SOLVED] Macro to generate a random number between 2 specific values into specific cells.
    By Nerfmagnet in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 04-10-2013, 11:45 AM
  6. Replies: 1
    Last Post: 01-22-2013, 07:02 AM
  7. Excel generate random number with frequency
    By selman555 in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 05-03-2012, 04:23 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1