Generate Unique UID

jstevens
GoldLounger
Posts: 2628
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: 78412
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
Best wishes,
Hans

jstevens
GoldLounger
Posts: 2628
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: Generate Unique UID

Post by jstevens »

Hans,

Brilliant solution!
Regards,
John