Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generate unique ID in VBA (particular format)

I want to write VBA script and add it to the button to get an random unique ID.

The sample format:

F-B829IB-BKC1
F-QLM9I4-EFCY

It should start with "F" ; "-" ; random 6 digits/letters ; "dash" ; random 4 digits/letters

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance for your assistance.

>Solution :

Here is a function that you might be able to apply to your needs:

Function RandID() As String
    Dim pool As String
    Dim id As String
    Dim i As Long, n As Long
    
    pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    n = Len(pool)
    id = "F-"
    For i = 1 To 11
        If i = 7 Then
            id = id & "-"
        Else
            id = id & Mid(pool, Application.WorksheetFunction.RandBetween(1, n), 1)
        End If
    Next i
    RandID = id
    
End Function

Typical output: F-I8FTLX-3E81.

These IDs are on the short side. Uniqueness isn’t guaranteed, especially if a large number of IDs are to be generated. The total number of IDs is 36^10, so you are probably safe for small-scale use.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading