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 ExplicitPrivate Declare Function UuidCreate Lib _ "rpcrt4.dll" (pId As UUID) As LongPrivate Declare Function UuidToString Lib _ "rpcrt4.dll" Alias "UuidToStringA" (uuidID _ As UUID, ppUuid As Long) As LongPrivate Declare Function RpcStringFree Lib _ "rpcrt4.dll" Alias "RpcStringFreeA" _ (ppStringUuid As Long) As LongPrivate Declare Function CopyMemory Lib _ "kernel32.dll" Alias "RtlMoveMemory" (pDst _ As Any, pSrc As Any, ByVal nSize As Long) _ As LongPrivate Type UUID Data1 As Long Data2 As Long Data3 As Long Data4(8) As ByteEnd TypePublic Function GenUuid(sUuid As String) As _ Boolean 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, _ SZ_UUID_LEN If RpcStringFree(ppUuid) = RPC_S_OK Then sUuid = sUid GenUuid = True End If End If End IfEnd Function
Use the function like this:
Dim sId As StringCall 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.