Macro to generate random serial number

dudumomo

Board Regular
Joined
Jun 3, 2014
Messages
65
Hi guys,

I need to generate some serial number to provide to our students and I'm looking for a macro to do it.

Ideally, I enter in cell A1 the number of key code to generate and it will generate those in the following format:
3XA7-BC6D-98EF
Can mix letter (Capital only) and number.
But should exclude 0 and O, 5 and S, and 1 and I
(Easier for them)

And cherry on the top, it keeps all the previously generated serial number to make sure it will not generate twice the same.

Do you have some idea to do that?

Thanks!
 
Hey Jerry,

this thread is some month old, but i hope you're still here. :D This macro is almost perfect, but it need some modification i could'nt figure out by myself. Maybe you can help me?
I need following pattern: TEST-XXXX-XXXX-XXXX . The first 4 chars are static, the rest must be numbers that are divisible by given numbers. B1=3 (next 4), C1=4 (next 4), D1=5 (next 4).

For example: TEST-3708-1028-2845

is this possible? thank you very much for taking the time.
 
Upvote 0

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
this is the code i've so far:

Code:
Sub MakeSerialNbrs()
'--generates a user specfied number of unique serial numbers
'  serial numbers meet criteria in function: sGenerateSerialNbr
'  eg: TEST-86496-64903-47185 with excluded characters
 Dim bUniqueCodeFound
 Dim lNdx As Long, lSerialNbrsToMake As Long
 Dim rResults As Range
 Dim dctSerialNbrs As Scripting.Dictionary
 Dim sSerialNbr As String
 Dim wks As Worksheet
  
 Set dctSerialNbrs = New Scripting.Dictionary
 Set wks = ActiveSheet
 
 On Error GoTo ExitProc
 With wks
   lSerialNbrsToMake = .Range("A1").Value
   '--location to write results
   Set rResults = .Range("A3")
   '--optional: clear previous results
   '  Range(rResults, .Cells(.Rows.Count, rResults.Column)).ClearContents
 End With

'--generate specified count of serial numbers.
'  use dictionary to test each number is unique
 For lNdx = 1 To lSerialNbrsToMake
   bUniqueCodeFound = False
   Do Until bUniqueCodeFound
      '--call function to get string meeting criteria
      sSerialNbr = sGenerateSerialNbr()
      If Not dctSerialNbrs.Exists(sSerialNbr) Then
         dctSerialNbrs.Add sSerialNbr, lNdx
         bUniqueCodeFound = True
      End If
   Loop
 Next lNdx
   
'--write results
 If dctSerialNbrs.Count > 0 Then
   rResults.Resize(dctSerialNbrs.Count).Value _
     = Application.Transpose(dctSerialNbrs.Keys)
 End If
 
ExitProc:
 If Err.Number <> 0 Then
   Set dctSerialNbrs = Nothing
   MsgBox Err.Number & "-" & Err.Description
 End If
End Sub

Private Function sGenerateSerialNbr() As String
'--generates a random string meeting the specified
'    pattern and character exclusions
'
   Dim bValidCodeFound As Boolean
   Dim lCode As Long, lPos As Long
   Dim sSerialNbr As String
   Const sPattern As String = "xxxxx-xxxxx-xxxxx"
      
   For lPos = 1 To Len(sPattern)
      If Mid$(sPattern, lPos, 1) = "-" Then
         sSerialNbr = sSerialNbr & "-"
      Else
         bValidCodeFound = False 'reset
         Do Until bValidCodeFound
            '--get random nbr representing char code from "0" and "9"
            lCode = Application.RandBetween(48, 57)
            
            '--test if lCode represents excluded char
            Select Case lCode
               ' Case 58, 59, 60, 61, 62, 63, 64 'exclude ":" to "@"
               Case Else:
                  bValidCodeFound = True
            End Select
         Loop
         sSerialNbr = sSerialNbr & Chr$(lCode)
      End If
   Next lPos
   
   sGenerateSerialNbr = "TEST-" & sSerialNbr
End Function

I've no idea how to insert the divisible function. Can somebody help me please?
 
Last edited:
Upvote 0
Hi derox,

Try using these two functions with the Sub MakeSerialNbrs that you currently have. Delete your previous version of the function sGenerateSerialNbr.

Code:
Private Function sGenerateSerialNbr() As String
'--generates a random string meeting the specified
'    pattern TEST-"#####-#####-#####"
'  where the 3 numbers represented by the group of #'s are evenly
'  divisible 3, 4, and 5 respectively
'
   Dim lDivisor As Long
   Dim sReturn As String, sPart As String
   
   sReturn = "TEST"
   
   For lDivisor = 3 To 5
      sPart = lGenerateDivisibleNbr(lMin:=0, lMax:=99999, _
         lDivisor:=lDivisor)
      If Len(sPart) = 0 Then
         sReturn = 0
         GoTo ExitProc
         Exit Function
      Else
         sReturn = sReturn & "-" & sPart
      End If
   Next lDivisor
   
ExitProc:
   sGenerateSerialNbr = sReturn
End Function

Private Function lGenerateDivisibleNbr(ByVal lMin As Long, _
   ByVal lMax As Long, ByVal lDivisor As Long) As String
'--generate random number that is in range of lMin to lMax (exclusive) and
'     can be evenly divided by lDivisor
   
   Dim lMinDiv As Long, lMaxDiv As Long, lRndResult As Long
   Dim sReturn As Variant
   
 '--validate inputs
 If lMin < 0 Or lMin > lMax Or lDivisor < 1 Then
   sReturn = vbNullString
   GoTo ExitProc
 End If
   
 '--calculate smallest and largest divisors that can be multiplied
 '  by lDivisor with result in range of lMin to lMax
 lMinDiv = Application.RoundUp(lMin / lDivisor, 0)
 lMaxDiv = Fix(lMax / lDivisor)
 lRndResult = Application.RandBetween(lMinDiv, lMaxDiv) * lDivisor
 
 '--format result to same number of characters as lMax
 sReturn = Format(lRndResult, String(Len(CStr(lMax)), "0"))
 
ExitProc:
   lGenerateDivisibleNbr = sReturn
End Function
 
Last edited:
Upvote 0
Hi Jerry,

I can replace "TEST" with a variable from a drop down in cell B1 to represent a department ID.

Can't figure how to change "#####-#####-#####" to something different, ie. "##-#-###" or such.

Thanks,
Howard


Code:
'    pattern TEST-"#####-#####-#####"


Code:
Private Function sGenerateSerialNbr() As String
'--generates a random string meeting the specified
'    pattern TEST-"#####-#####-#####"
'  where the 3 numbers represented by the group of #'s are evenly
'  divisible 3, 4, and 5 respectively
'
   Dim lDivisor As Long
   Dim sReturn As String, sPart As String
   
   sReturn = Range("B1") '"TEST"
   
   For lDivisor = 3 To 5
      sPart = lGenerateDivisibleNbr(lMin:=0, lMax:=99999, _
         lDivisor:=lDivisor)
      If Len(sPart) = 0 Then
         sReturn = 0
         GoTo ExitProc
         Exit Function
      Else
         sReturn = sReturn & "-" & sPart
      End If
   Next lDivisor
   
ExitProc:
   sGenerateSerialNbr = sReturn
End Function
 
Upvote 0
thank you very much jerry, i will try at home and give a feedback. i'm not completly sure, but what i see is that the ldvisior isn't flexible, group one should be divisible by .Range("B1").Value (3), group two by .Range("C1").Value (4) and group three .Range("C1").Value (5). Maybe i can figure this out by myself. the biggest problem was the spart.

@Howard
Try the first script on page 1. edit the pattern to xx-x-xxxx and at the end replace sGenerateSerialNbr = .Range("B1").Value & sSerialNbr
 
Last edited:
Upvote 0
Hi Jerry,

@Howard Try the first script on page 1. edit the pattern to xx-x-xxxx and at the end replace sGenerateSerialNbr = .Range("B1").Value & sSerialNbr


Thanks, that works fine. Had to drop the . (dot) from .Range(...)

Regards,
Howard
 
Upvote 0
Hey Jerry,

i've tried the code and it works like expected, but does it only works continously? I mean this part: For lDivisor = 3 To 5, is it possible to say that first part is divisible with 3, second part with 6 and third part with 5? my fault to give you the numbers 3,4,5.

thank you very much for taking the time.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,221,418
Messages
6,159,791
Members
451,589
Latest member
Harold14

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