Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this code ever repeat a value? I need a Number that will never repeat and does not require a stored variable

Tags:

excel

vba

Looking to generate a unique value to save quoted orders with, allowing easy recall. Will this number ever repeat, other than when clicked within 1 second.

idNumber = Application.Worksheetfunction.Roundup(DateValue(Now) * TimeValue(Now),0)
like image 390
James Schuster Avatar asked Dec 08 '22 14:12

James Schuster


1 Answers

Depending on your actual needs, unique values may not need to be Long integers; if that's so then it's good to know that Windows has a built-in way (in OLE32.DLL) of generating them, that you can leverage to generate Globally Unique IDentifiers:

Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
End Type

Private Declare Function CoCreateGuid Lib "OLE32.DLL" (pGuid As GUID) As Long

Public Function GetGUID() As String
'(c) 2000 Gus Molina

    Dim udtGUID As GUID

    If (CoCreateGuid(udtGUID) = 0) Then

        GetGUID = _
            String(8 - Len(Hex$(udtGUID.Data1)), "0") & Hex$(udtGUID.Data1) & _
            String(4 - Len(Hex$(udtGUID.Data2)), "0") & Hex$(udtGUID.Data2) & _
            String(4 - Len(Hex$(udtGUID.Data3)), "0") & Hex$(udtGUID.Data3) & _
            IIf((udtGUID.Data4(0) < &H10), "0", "") & Hex$(udtGUID.Data4(0)) & _
            IIf((udtGUID.Data4(1) < &H10), "0", "") & Hex$(udtGUID.Data4(1)) & _
            IIf((udtGUID.Data4(2) < &H10), "0", "") & Hex$(udtGUID.Data4(2)) & _
            IIf((udtGUID.Data4(3) < &H10), "0", "") & Hex$(udtGUID.Data4(3)) & _
            IIf((udtGUID.Data4(4) < &H10), "0", "") & Hex$(udtGUID.Data4(4)) & _
            IIf((udtGUID.Data4(5) < &H10), "0", "") & Hex$(udtGUID.Data4(5)) & _
            IIf((udtGUID.Data4(6) < &H10), "0", "") & Hex$(udtGUID.Data4(6)) & _
            IIf((udtGUID.Data4(7) < &H10), "0", "") & Hex$(udtGUID.Data4(7))
    End If

End Function

source

If two values ever collide, you better have a lottery ticket!

like image 72
Mathieu Guindon Avatar answered May 02 '23 15:05

Mathieu Guindon