Macros Serial number generation with repeatability comparison base

K0st4din

Well-known Member
Joined
Feb 8, 2012
Messages
501
Office Version
  1. 2016
  2. 2013
  3. 2011
  4. 2010
  5. 2007
Platform
  1. Windows
Hi all, after a lot of searching I managed to find something similar on the site that comes close to what I want to do.


But since I don't understand anything, I can't even modify it for my needs, I am asking for your macro help.
I will attach my excel file.
I want to generate random serial numbers and in different situations with different character lengths ie 12 or 14 or 16 or 18.
In cell I2 I have made a drop down menu to choose how many characters to be. In cell J2 - what type should they be (ie Only uppercase letters and numbers, only numbers or lowercase, uppercase and numbers, or some of my choice of selected characters, etc.).
In cell K2, I record how many Countless combinations to generate according to the choices made that start from/in cell A1 to the end (just an example: be it 3, 34569 or 1 million).
Here it comes (and what I was able to find on the site) is to be able in the second worksheet (with some name given by me) to be able to accumulate a base, with already generated combinations, so that there is never repetition in the new ones generated.
Since I have no idea if the macro can add columns, I have made several of the different types of combinations, be it 12, 14, 16 or 18. If after the first column is filled, the macro can add a new column with the search criteria, then it will make no sense for me to put columns for each type (but I leave this as a last touch, to have your say).
I would be extremely grateful if you could help me.
One more thing, in the link where I found a similar solution, there the user requires to have some hyphens, in my case, I don't need them, that is, I need something like this: for example: ODN81T6DRJJY8S or ODN81T6DRJJY8S49 or 068249317896) i.e. is without any signs.
Thanks in advance to each one!
Test serial numbers.xlsm
ABCDEFGHIJKLMNOP
1? CombinationSelect model letters and numbersHow many numbers you need12ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
214ABCDEFGHIJKLMNOPQRSTUVWXYZ012345678998725414ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
316abcdefghijklmnopqrstuvwxyz0123456789
4180123456789
5
6
7
8
9
10
generate numbers
Cells with Data Validation
CellAllowCriteria
I2List=$N$1:$N$5
J2List=$O$1:$O$11



Test serial numbers.xlsm
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1121212121212121214141414141414141616161616161616
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
base generated numbers
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
I haven't looked at your linked thread. It's always better to tell us exactly what you want, rather than pointing us to something different.

If you're not comfortable with VBA, you could do this entirely in Excel.

The chances of duplicates are slim - for the example shown, there are 4.7E+18 permutations!

Let us know if this is on the right lines, and whether you still want a VBA solution (which will be relatively simple).

Cell Formulas
RangeFormula
C2C2=IF(MAX(C4:C21)>1,"Yes","None")
C4:C21C4=COUNTIF(D4:D21,D4)
D4:D21D4=CONCATENATE(E4,F4,G4,H4,I4,J4,K4,L4,M4,N4,O4,P4)
E4:P21E4=INDEX(MyChars,RANDBETWEEN(1,36))
Named Ranges
NameRefers ToCells
MyChars=Sheet1!$A$2:$A$37E4:P21
 
Upvote 0
Hi StephenCrump,
I'm definitely looking for a macro that will do what I want. Now, the link definitely doesn't matter at all, but there the macro, it also made a database, that's why I showed it. Ok, I think I have described everything in great detail, exactly what I want to happen in my workbook. I remain available if you have questions and something is not clear from what I wrote. Be alive and well. Thank you very much!
 
Upvote 0
Give this a try. The Scripting Dictionary will prevent duplicates.

ABCD
1CharactersOutput
2AZSdiDRkLmhPPk
3azeJdTVwPML835
409UuH0DY2qayTj
5CodesbDDJZKvGpTxy
66590YCVSt0neQHam
797122mEz7TJQs7nyV
84857lZm1aBuqiILc
9S6BYZHFj31pw
10tKcYIg7j3l0u
11Cb1UotvmJYjC
12hZJmJ55lbf5f
13PzCPEZepvrpJ
14bdHpkWy1bomo
15qaJxP0r7kujx
163eih58qksCTf
173ARP3ehkvf1x
186xypZZHmKeFQ
19vZcAPEVDUdfl
20qj7TqUj9QDRg
21B8KHoFHukKgz
22
Sheet1
Cell Formulas
RangeFormula
A6:B8A6=CODE(A2)

VBA Code:
Sub Test()

    Dim c As Variant
    Dim s() As String
    Dim N As Long, L As Long, i As Long, j As Long, count As Long
    
    N = 20  'Number
    L = 12  'Length
    c = Range("Codes").Value
    
    For i = 1 To UBound(c)
        count = count + c(i, 2) - c(i, 1) + 1
    Next i
    ReDim s(1 To count)
    
    count = 0
    For i = 1 To UBound(c)
        For j = c(i, 1) To c(i, 2)
            count = count + 1
            s(count) = Chr(j)
        Next j
    Next i
    
    c = MakeCodes(N, L, s)
    
    On Error Resume Next
    Range("MyCodes").ClearContents
    On Error GoTo 0
    
    With Range("D2").Resize(UBound(c) - LBound(c) + 1)
        .Value = c
        .Name = "MyCodes"
    End With
    
End Sub
Function MakeCodes(N As Long, L As Long, s() As String) As Variant
    
    Dim d As Scripting.Dictionary
    Dim tmp As String
    Dim i As Long
    
    Set d = New Scripting.Dictionary
    d.CompareMode = vbBinaryCompare
    Randomize
    
    Do Until d.count = N
        tmp = ""
        For i = 1 To L
            tmp = tmp & s(1 + Int(UBound(s) * Rnd()))
        Next i
        d(tmp) = tmp
    Loop

    MakeCodes = Application.Transpose(d.Items)

End Function
 
Upvote 0
Hello again,
I'm very sorry, but the macro made like this is quite difficult for me to understand.
The second, which is that it is not like what I have shown in the example, but quite different.
The next thing, in the already generated numbers shown, there is a combination of uppercase, lowercase letters and numbers. (here I want to control what is displayed as in my table)
The next thing is that in my idea, I don't have to go in and change how many characters I want and how many numbers in the macro itself I mean this line:
N = 20 'Number
L = 12' Length.
In the macro, I also do not see where the information is accumulated from already generated such numbers. (because, for example, today I may generate 5600 numbers, and another day 15,765).
It's a lot more flexible in my way.
What I really like about the site is that you say, and even you said it to me, that you didn't enter the link because it's more important what exactly we want to do or get as a result.
However, in this case, even you are offering me something radically different from what I am trying to achieve and I have tried to describe in detail and attached the tables.
I remain available and thanks in advance!
 
Upvote 0
.. you are offering me something radically different from what I am trying to achieve ....
Really?

If you just want capital letters and numerics, length 14, you simply need to change the code L = 14 'Length and the workbook:
ABCD
1CharactersOutput
2AZ0AIGQO057T5FM9
309YQSMICD0BD7WPD
408NZ8RRT7INUIU
5Codes9MO8S5ZUMSOZOH
66590DYT3M5OATEPDFF
74857DG9UN355YQW2XW
8D3W8VBA1SMDZJV
9EZNIQF6HFQB70V
10CZHIPGJ1FN44SS
117G6UTK6Z963ELH
12IJI047BKZA3AWL
13C9YTQ4IZ12AYG2
14SA57YAYJYEFYHP
153E0S0BIUHCBX2C
168LXI1Q6TYMWUO9
17VMHV4SKX58R1ZL
18ECYCC24XLHP9SQ
19UD1EPF9YNVCOSW
200KR8IVQYVJMQA3
21PEQPCHUHXA3380
Sheet1
Cell Formulas
RangeFormula
A6:B7A6=CODE(A2)

In any event, it's standard coding practice to parameterise variables, e.g. compared to having numbers like 14 littered throughout the code. And similar for Excel models - a couple of keystrokes here and we can use any combination of characters/numbers you care to choose.

I also do not see where the information is accumulated from already generated such numbers. (because, for example, today I may generate 5600 numbers, and another day 15,765).
That's a next step, and can be done in different ways. Probably the easiest would to generate a large bank (perhaps 1,000,000 unique codes) and draw from these. Once exhausted, generate another bank, check for duplicates (unlikely) and draw from this bank etc.
 
Upvote 0
Hello,
you are super.
Since you're writing the code, it wasn't clear to me how to specify what to generate (is it Uppercase letters and numbers only or whatever), but from the example I can now see that if I remove the last line A :B 4, things happen. (can one more line be added here, for example A:B 5, in which, for example, if I put K-W, it will only do between this range or if I do it in A:B - it will be K-W, it will read only this choice (this is just a question and if possible as an option)

The other thing that is not clear to me is where this information is taken from and it shows me these numbers of Codes A6:B7 or B8 (depending on what the choice is)

Before writing I tried the macro but it gives me this error.

2024-07-25_125711.jpg

Am I not seeing or adding something?

As for the repeatability check, I'm worried (it has happened to me sometimes) that the button on the macro will be pressed and things will go wrong so that the previous info is lost.
For this reason, I wanted whatever happens after the desired numbers and characters are generated to save them somewhere and whatever happens to be able to check for repeatability.
Here I am adding what I have done so far for the 2nd accumulation worksheet. But now I have another idea.
For example, to create a worksheet with only 14 characters when they are, to create a worksheet with 16 characters, etc. and there to collect, so far generated (I am open to ideas and suggestions to reach a final ).

As for what you wrote about it being quite different from my idea, I didn't mean to offend you, it's just very different from mine.
On the contrary, I have the best feelings.
I remain available until we reach the end!
 
Upvote 0
I didn't mean to offend you
You didn't. Not at all.

The error in your code is because I have an Excel named range called "Codes". Sorry, this should have come up in the XL2BB screenshot, but sometimes this doesn't work for me (a dodgy clipboard, I think).

Have a play with the workbook attached: Codes.xlsm | Powered by Box

Codes.xlsm
AB
1Input
2CharactersABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
3Length14
4Number15
5Save to Vault?TRUE
6
7Output
87MC49QE37R4V7X
99J7AHE8GA9149Q
10UGGVEU57G2TM5A
11AZ1V6QYXNMKFC2
12RHMELQWL9BH0LQ
13GSF3XYMSD9Z3HZ
14PA15WV4TF1LRYL
15PEDS7V7PFIMQSE
16EBFAA1BTLS8Q0D
17GON582F8Y5MM8G
18OPBFD4WBZQ1B0T
19CXZQDNGKHVE5NX
20TDQLHRVN11AUFD
215XBHT607AYJCUK
22ZI5HZJBONWCCLL
23
Generate


Range names
Characters:
=Generate!$B$2
Length: =Generate!$B$3
No: =Generate!$B$4
SaveToVault: =Generate!$B$5
PutResultsHere:=Generate!$B$8

Cell B2 now lets you put in the characters you want to use, which is your original idea.

If SaveToVault is set to TRUE, the results will be saved and time-stamped into the "Vault" worksheet.

I have added a Sub called CheckVault, which as the name implies, checks the vault for duplicates. I have purposely created two duplicates, as highlighted, to test this functionality.

Codes.xlsm
ABCD
126 Jul 2024 14:31:4726 Jul 2024 14:31:5326 Jul 2024 14:31:57
2C0R3K618MUPHE7NHWYZPQ6HX4XNH7MC49QE37R4V7X
3S368TSYTUSYVJC9J7AHE8GA9149Q9J7AHE8GA9149Q
4OZQ8N54S3P5Y8O9OSD7IPNGKJNARUGGVEU57G2TM5A
58O9CCKETGR79S6WTFV74TU6WQNFIAZ1V6QYXNMKFC2
660QQI9J3AJWJR349JJ5Z6B1YLD6TRHMELQWL9BH0LQ
7V4TT6Z0ZL4IXP7BGFV3MN74MODGLGSF3XYMSD9Z3HZ
8F3RNF805L107FRPA15WV4TF1LRYL
9G36E3YKRW6C6H4PEDS7V7PFIMQSE
10O4YU9CQGX1RCLDOPBFD4WBZQ1B0T
111V6C992MRSL1S2GON582F8Y5MM8G
12OPBFD4WBZQ1B0T
13CXZQDNGKHVE5NX
14TDQLHRVN11AUFD
15aaaaaaaaaaaaaa<-- case sensitive, no duplicate
16AAAAAAAAAAAAAA
17
Vault


VBA Code:
Sub Test()

    Dim s As Variant, c As Variant
    Dim L As Long, LastCol As Long, N As Long
    Dim r As Range
    
    N = Range("No").Value
    L = Range("Length").Value
    s = Split(StrConv(Range("Characters").Value, vbUnicode), Chr(0))
    ReDim Preserve s(UBound(s) - 1)
    
    c = MakeCodes(N, L, s)

    On Error Resume Next
    Range("MyCodes").ClearContents
    On Error GoTo 0

    With Range("PutResultsHere").Resize(N)
        .Value = c
        .NumberFormat = String(L, "0") 'show leading zeros if code is all-numeric
        .Name = "MyCodes"
    End With
    
    If Range("SaveToVault").Value Then
        With Worksheets("Vault")
            Set r = .Cells(1, Columns.count).End(xlToLeft)
            With .Columns(r.Column + IIf(Len(r), 1, 0))
                .Cells(2).Resize(N).Value = c
                .AutoFit
                .NumberFormat = String(L, "0")
                .Cells(1).Value = Now()
                .Cells(1).NumberFormat = "d mmm yyyy hh:mm:ss"
            End With
        End With
    End If
    
End Sub
Function MakeCodes(N As Long, L As Long, s As Variant) As Variant
    
    Dim d As Scripting.Dictionary
    Dim tmp As String
    Dim i As Long
    
    Set d = New Scripting.Dictionary
    d.CompareMode = vbBinaryCompare
    Randomize
    
    Do Until d.count = N
        tmp = ""
        For i = 1 To L
            tmp = tmp & s(Int((UBound(s) - LBound(s) + 1) * Rnd()))
        Next i
        d(tmp) = tmp
    Loop

    MakeCodes = Application.Transpose(d.Items)
    
End Function
Sub CheckVault()
    
    Dim d As Scripting.Dictionary
    Dim vIn As Variant
    Dim r As Long, c As Long, count As Long
    Dim Dups As String
    
    Set d = New Scripting.Dictionary
    d.CompareMode = vbBinaryCompare
    vIn = Worksheets("Vault").Range("A1").CurrentRegion.Value
    
    For c = 1 To UBound(vIn, 2)
        For r = 1 To UBound(vIn)
            If vIn(r, c) = "" Then Exit For
            On Error Resume Next
            d.Add vIn(r, c), vIn(r, c)
            If Err Then
                Dups = Dups & vIn(r, c) & vbLf
                count = count + 1
            End If
            On Error GoTo 0
        Next r
    Next c
    
    MsgBox count & " duplicates" & vbLf & vbLf & Dups

End Sub
 
Upvote 1

Forum statistics

Threads
1,220,965
Messages
6,157,119
Members
451,398
Latest member
rjsteward

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