CreateGuid


Description:
This function is a simple wrapper function to wrap the API work of calling CoCreateGuid to return a string representation of a GUID. Simple returns the new GUID.
 
Code:
Option Explicit

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

Declare Function CoCreateGuid Lib "ole32" (pguid As GUID) As Long
Declare Function UuidToString Lib "rpcrt4" Alias "UuidToStringA" (pguid _
        As GUID, pszGuid As Long) As Long
Declare Function RpcStringFree Lib "rpcrt4" Alias "RpcStringFreeA" (psz _
        As Long) As Long
Declare Function CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest _
        As Any, src As Any, ByVal length As Long) As Long
Declare Function CopyLongToString Lib "kernel32" Alias "lstrcpyA" _
        (ByVal lpString1 As String, lpString2 As Any) As Long

Public Function CreateGuid() As String
    
    Dim TheGuid As GUID
    Dim pszGuid As Long
    
    CoCreateGuid TheGuid
    UuidToString TheGuid, pszGuid
    
    CreateGuid = Space(256)
    CopyLongToString CreateGuid, ByVal pszGuid
    
    RpcStringFree pszGuid
    CreateGuid = _
       Mid(CreateGuid, 1, InStr(1, CreateGuid, vbNullChar) - 1)
    
End Function
 
Sample Usage:
 
    Debug.Print CreateGuid