Visual Basic 6 function "StringFromGUID"

Go back

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

Attribute VB_Name = "modStringFromGUID"
' 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

''
' Completes a string by adding zero characters to the front
' @param    string  value       The input string
' @param    integer length      The length the return value must be
' @param    string  character   Optional, the character that should be used for filling, default: "0"
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function zerofill(ByVal value As String, ByVal length As Integer, Optional ByVal character = "0") As String
    If Len(value) >= length Then zerofill = value: Exit Function
    Dim i As Integer
    Do
        value = character & value
    Loop While Len(value) < length
    zerofill = value
End Function

''
' Converts a binary GUID to a String
' @param    string  binary      The binary string, must be 16 bytes
' @return   string              A GUID representation of the binary data
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function StringFromGUID(ByVal binary 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
    
    ' The first part
    s = Left(binary, 4)
    For i = 4 To 1 Step -1
        ret = ret & zerofill(Hex(Asc(Mid(s, i, 1))), 2)
    Next i
    ret = ret & "-"
    ' The second part
    s = Mid(binary, 5, 2)
    For i = 2 To 1 Step -1
        ret = ret & zerofill(Hex(Asc(Mid(s, i, 1))), 2)
    Next i
    ret = ret & "-"
    ' The third part
    s = Mid(binary, 7, 2)
    For i = 2 To 1 Step -1
        ret = ret & zerofill(Hex(Asc(Mid(s, i, 1))), 2)
    Next i
    ret = ret & "-"
    ' The forth part
    s = Right(binary, 8)
    For i = 1 To 8
        ret = ret & zerofill(Hex(Asc(Mid(s, i, 1))), 2)
    Next i
    
    StringFromGUID = Left(ret, 23) & "-" & Right(ret, 12)
End Function