Welcome to W3Courses
 Like Us on Facebook

Source Code for Creating a GUID in VBA

Following is the source code for creating a GUID in VBA:

 

 CODE

Option Compare Binary
Option Explicit
'------------------------------------------
'  basGuid from http://www.trigeminal.com/code/guids.bas
' You may use this code in your applications, just make
' sure you keep the (c) notice and don't publish it anywhere
' as your own
' Copyright (c) 1999 Trigeminal Software, Inc. All Rights Reserved
'------------------------------------------

' Note that although Variants now have
' a VT_GUID type, this type is unsupported in VBA,
' so we must define our own here that will have the same
' binary layout as all GUIDs are expected by COM to
' have.
Public Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
End Type
Public Declare Function StringFromGUID2 Lib "ole32.dll" _
    (rclsid As GUID, ByVal lpsz As Long, ByVal cbMax As Long) As Long
Public Declare Function CoCreateGuid Lib "ole32.dll" _
    (rclsid As GUID) As Long
'------------------------------------------------------------
'   StGuidGen
'
'   Generates a new GUID, returning it in canonical
'   (string) format
'------------------------------------------------------------
Public Function GetSQLGUID(vGUID As Variant) As String
    On Error GoTo GetSQLGuid_Error
    GetSQLGUID = " '" & Left(Right(StringFromGUID(vGUID), 39), 38) & "' "
    Exit Function
GetSQLGuid_Error:
    GetSQLGUID = ""
End Function
Public Function GetStringFromGUID(vGUID As Variant) As String
    On Error GoTo GetStringFromGuid_Error
    GetStringFromGUID = Left(Right(StringFromGUID(vGUID), 39), 38)
    Exit Function
GetStringFromGuid_Error:
    GetStringFromGUID = ""
End Function
Public Function StGuidGen() As String
    Dim rclsid As GUID
    If CoCreateGuid(rclsid) = 0 Then
        StGuidGen = StGuidFromGuid(rclsid)
    End If
End Function

'------------------------------------------------------------
'   StGuidFromGuid
'
'   Converts a binary GUID to a canonical (string) GUID.
'------------------------------------------------------------
Public Function StGuidFromGuid(rclsid As GUID) As String
    Dim rc As Long
    Dim stGuid As String
    ' 39 chars  for the GUID plus room for the Null char
    stGuid = String$(40, vbNullChar)
    rc = StringFromGUID2(rclsid, StrPtr(stGuid), Len(stGuid) - 1)
    StGuidFromGuid = Left$(stGuid, rc - 1)
End Function

Example Use:

 CODE

dim strGUID as string
strGUID = StGuidGen() 

Share