Generate Unique UID

jstevens
SilverLounger
Posts: 2467
Joined: 26 Jan 2010, 16:31
Location: Southern California

Generate Unique UID

Post by jstevens »

I'm looking for an Excel VBA solution to generate a unique UID number for an ICS file.

Example Format: UID:5FC53010-1267-4F8E-BC28-1D7AE55A7C99

Your thoughts are appreciated.
Regards,
John

User avatar
HansV
Administrator
Posts: 72885
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Generate Unique UID

Post by HansV »

Here is some code. The type and API declarations should be at the top of a module (below Option Explicit):

Code: Select all

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

Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As LongPtr
Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr

Function CreateGuid() As String
    Dim Guid As GUID_TYPE
    Dim strGuid As String
    Dim retValue As LongPtr
    Const guidLength As Long = 39
    retValue = CoCreateGuid(Guid)
    If retValue = 0 Then
        strGuid = String(guidLength, vbNullChar)
        retValue = StringFromGUID2(Guid, StrPtr(strGuid), guidLength)
        If retValue = guidLength Then
            CreateGuid = "UID:" & Mid(strGuid, 2, Len(strGuid) - 3)
        End If
    End If
End Function
Regards,
Hans

jstevens
SilverLounger
Posts: 2467
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: Generate Unique UID

Post by jstevens »

Hans,

Brilliant solution!
Regards,
John