Visual Basic 6 function "GUIDFromString"

Go back

Below you'll find the source for the Visual Basic 6 function GUIDFromString.

Attribute VB_Name = "modGUIDFromString"
' These functions are downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' Converts a heximal string to a decimal integer
' Same syntax as the PHP function 'hexdec'
' See also: http://www.php.net/manual/en/function.hexdec.php
' @param    String  hex_string      The heximal string
' @return   Integer                 An integer value
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function hexdec(hex_string As String) As Integer
    hexdec = Val("&h" & hex_string)
End Function

''
' Converts a String to a binary GUID
' @param    string  GUID        The GUID, for example "{01234567-89AB-CDEF-0123-456789ABCDEF}"
' @return   string              A binary string, always 16 bytes
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function GUIDFromString(ByVal GUID As String) As String
    ' The return value will be built in here
    Dim ret As String
    ' Multiple used variables
    Dim s As String, i As Integer
    ' Removes some formatting characters
    GUID = Replace(GUID, "-", "")
    If Left(GUID, 1) = "{" And Right(GUID, 1) = "}" Then GUID = Mid(GUID, 2, Len(GUID) - 2)
    ' The first part
    s = Left(GUID, 8)
    For i = 7 To 1 Step -2
        ret = ret & Chr(hexdec(Mid(s, i, 2)))
    Next i
    ' The second part
    s = Mid(GUID, 9, 4)
    For i = 3 To 1 Step -2
        ret = ret & Chr(hexdec(Mid(s, i, 2)))
    Next i
    ' The third part
    s = Mid(GUID, 13, 4)
    For i = 3 To 1 Step -2
        ret = ret & Chr(hexdec(Mid(s, i, 2)))
    Next i
    ' The forth part
    s = Right(GUID, 16)
    For i = 1 To 15 Step 2
        ret = ret & Chr(hexdec(Mid(s, i, 2)))
    Next i
    
    GUIDFromString = ret
End Function