guid excel code example

Example: How can I generate GUIDs in Excel

'Native and fast VBA function to create a GUID / UUID 
'that does not rely upon Scriptlet.TypeLib or any external library.

'Call the function like so:

MsgBox GUID


Function GUID$(Optional lowercase As Boolean, Optional parens As Boolean)
    Dim k&, h$
    GUID = Space(36)
    For k = 1 To Len(GUID)
        Randomize
        Select Case k
            Case 9, 14, 19, 24: h = "-"
            Case 15:            h = "4"
            Case 20:            h = Hex(Rnd * 3 + 8)
            Case Else:          h = Hex(Rnd * 15)
        End Select
        Mid$(GUID, k, 1) = h
    Next
    If lowercase Then GUID = LCase$(GUID)
    If parens Then GUID = "{" & GUID & "}"
End Function

'------------------------------------------------------------------

'Notes:  Called with no arguments, the function returns a string.
'        GUID() looks like:
'        A0077A2B-5935-4BDA-9333-4FDF81C23418
'        3c763963-7a55-41c5-a04e-401955387e5c	

'        GUID(1) looks like:
'        3c763963-7a55-41c5-a04e-401955387e5c	

'        GUID(, 1) looks like:
'        {4B98B15B-8B21-49A4-ACEB-58879135D227}

'        GUID(False, True) looks like:
'        {3256a225-76e4-4906-91ad-dcea8a377cdd}


'Caveat: This function generates a Version 4 (random) GUID / UUID.
'        Version 4 GUIDs should only be used for identification
'        and not security.
  
'References:  
'        http://guid.one/guid
'        https://www.ietf.org/rfc/rfc4122.txt 
'        https://en.wikipedia.org/wiki/Universally_unique_identifier 
'        https://betterexplained.com/articles/the-quick-guide-to-guids/

Tags:

Html Example