Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Advanced
Nov 5, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Generate Unique String IDs

If you need unique string IDs and don't have a sure-fire way of either generating or guaranteeing the generated ID is unique, then you need a Universally Unique ID (UUID) or Globally Unique ID (GUID) as Microsoft calls them. A UUID is a 128-bit number that's generated based on a time value and your computer's network interface card (NIC) and is guaranteed to be unique (at least within your network and until about the year 3400).

This routine generates UUIDs and converts them into 36-byte strings. Just paste this code into a module:

Option Explicit

Private Declare Function UuidCreate Lib _
	"rpcrt4.dll" (pId As UUID) As Long
Private Declare Function UuidToString Lib _
	"rpcrt4.dll" Alias "UuidToStringA" (uuidID _
	As UUID, ppUuid As Long) As Long
Private Declare Function RpcStringFree Lib _
	"rpcrt4.dll" Alias "RpcStringFreeA" _
	(ppStringUuid As Long) As Long
Private Declare Function CopyMemory Lib _
	"kernel32.dll" Alias "RtlMoveMemory" (pDst _
	As Any, pSrc As Any, ByVal nSize As Long) _
	As Long

Private Type UUID
	Data1 As Long
	Data2 As Long
	Data3 As Long
	Data4(8) As Byte
End Type

Public Function GenUuid(sUuid As String) As _
	Const RPC_S_OK As Long = 0
	Const SZ_UUID_LEN As Long = 36
	Dim uuidID As UUID
	Dim sUid As String
	Dim ppUuid As Long

	sUid = String(SZ_UUID_LEN, 0)
	If UuidCreate(uuidID) = RPC_S_OK Then
		If UuidToString(uuidID, ppUuid) = _
			RPC_S_OK Then
			CopyMemory ByVal sUid, ByVal ppUuid, _
			If RpcStringFree(ppUuid) = RPC_S_OK Then
				sUuid = sUid
				GenUuid = True
			End If
		End If
	End If
End Function
Use the function like this:
Dim sId As String
Call GenUuid(sId)
MsgBox "Id is " & sId 
I'm sure you can find better uses for the ID than just displaying it. But be aware that these numbers have the potential to uniquely identify the machine on which they were generated, raising security concerns. Depending on your customers and how you use the ID, this might not be an issue for you.
Edward Lennox
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date