This topic shows you how to create a GUID (Globally Unique IDentifier) from Visual Basic.

Microsoft Visual Basic 5.0Microsoft Visual Basic 4.0 32-bit

This document has been viewed times since February 22, 1998.
Last modified on February 22, 1998.

'At top level of a module, always include to be sure that all variables have the right type
Option Explicit

'Then declare these constants. GUID_OK is an error value check
Private Const GUID_OK As Long = 0

'and GUID_LENGTH holds the length of the GUID in bytes
Private Const GUID_LENGTH As Long = 38

'A GUID is made of following structure
Private Type GUID
    GUID1 As Long
    GUID2 As Integer
    GUID3 As Integer
    GUID4(0 To 7) As Byte
End Type

'Then we have to declare two functions, CoCreateGuid for actually getting the GUID
Private Declare Function CoCreateGuid Lib "ole32.dll" (pGUID As GUID) As Long

'and StringFromGUID2 for converting the GUID into a readable string
Private Declare Function StringFromGUID2 Lib "ole32.dll" (pGUID As GUID, ByVal PointerToString As Long, ByVal MaxLength As Long) As Long

'Then all we have to do is to write a public sub like this...
Public Function CreateNewGUID() As String

'Declare an error check variable lResult, a variable to hold the GUID
Dim lResultat As Long, uGUID As GUID

'and a string variable to hold the readable GUID
Dim sGUID As String

'Turn on error trapping
On Error Resume Next

'Call the GUID creating function and retreive both the GUID and error code
lResult = CoCreateGuid(uGUID)

'If error occured, return an empty string
If lResult <> GUID_OK Then
    CreateNewGUID = Empty
    Exit Function
End If

'OK, so far so good. Now prepare an empty string to hold the string GUID
sGUID = String$(GUID_LENGTH, 0)

'Call the converting function and place the string GUID into empty variable
lResult = StringFromGUID2(uGUID, StrPtr(sGUID), 1 + GUID_LENGTH)

'Then again, check error code for success or failure
If lResult <> 1 + GUID_LENGTH Then
    CreateNewGUID = Empty
Else
    CreateNewGUID = sGUID
End If

End Function

Please email me suggestions, improvements or anything else you want to be included on my pages.