I need a random number within a range, and not to duplicate the numbers in current list

Hi all! Here is what I am doing. Our students have a alternate student number which is what they use for email, computer login, etc... the syntax is the first four numbers are 1010 and the last four are the variable...for example 10102342 is one student and 10102393 could be a another student. The range is 10100001-10109999. I currently have just under 1000 students with 1010#'s already, so I would like to create a button on a form that would generate a 1010xxxx number without duplicating the current numbers.

Thanks in Advance!!



 My form has a text box (txtGenerate) which is the output; where the 1010# should show up. A command button (cmdGenerate) which is where the user will interact and click the button to generate the 1010#..

July 9th, 2013 11:26am

I have assumed that you have a list of students and their numbers somewhere - let's say that the existing numbers are in column D of a sheet named "Students", and that the new value goes at the bottom of column D:

Private Sub cmdGenerate_Click()
    Dim lngSNum As Long

GetNum:

    lngSNum = 10100000 + Int(Rnd() * 9999) + 1
    If IsError(Application.Match(lngSNum, Worksheets("Students").Range("D:D"), False)) Then
        Me.txtGenerate.Text = lngSNum
        MsgBox "The New random number is " & lngSNum
        Worksheets("Students").Cells(Rows.Count, "D").End(xlUp)(2).Value = lngSNum
    Else
        GoTo GetNum
    End If

End Sub


If you are actually storing the numbers as text and not numbers, this may require modification.




Free Windows Admin Tool Kit Click here and download it now
July 9th, 2013 12:42pm

Thanks to share the code to us. This will help the others who meet the same issue.
July 9th, 2013 10:02pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics