今天在http://access911.net/fixhtm/76FAB41E.htm (作者:朱亦文,爱狐狸,cg1)看到了VB生成GUID的两个方法,在这里转发下。同时,也谢谢作者朱亦文的分享。
方法1:
Debug.Print CreateObject("Scriptlet.TypeLib").Guid
方法2:
' --------------------------------------------------------------------
' Following Functions for Guid_Operation in this Module
'
' Function: CreateGuid() as string
' Function: StringToGuid(sGuid As String) As GUID
' Function: GuidToString(tGuid As GUID) As String
'
' Guid_OP by 等爱的狐狸
' 02/2/18
'
Option Explicit
Public Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(0 To 7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "ole32.dll" (tGUIDStructure As GUID) As Long
Private Declare Function StringFromGUID2 Lib "ole32.dll" (rguid As Any, ByVal lpstrClsId As Long, ByVal cbMax As Long) As Long
Private Declare Function CLSIDFromString Lib "ole32.dll" (pstCls As Long, clsid As GUID) As Long
Public Function CreateGUID() As String
Dim sGuid As String 'store result here
Dim tGuid As GUID 'get into this structure
Dim bGuid() As Byte 'get FORMatted string here
Dim lRtn As Long
Const clLen As Long = 50 ' In some Documents and BBs's the len may be short to 39
If CoCreateGuid(tGuid) = 0 Then 'use API to get the GUID
bGuid = String(clLen, 0)
lRtn = StringFromGUID2(tGuid, VarPtr(bGuid(0)), clLen) 'use API to FORMat it
If lRtn > 0 Then 'truncate nulls
sGuid = Mid$(bGuid, 1, lRtn - 1)
End If
CreateGUID = sGuid
End If
End Function
Public Function StringToGuid(sGuid As String) As GUID
Dim lRet As Long
lRet = CLSIDFromString(StrPtr(sGuid), StringToGuid)
End Function
Public Function GuidToString(tGuid As GUID) As String
Dim bGuid() As Byte
Dim lRtn As Long
Const clLen As Long = 50
bGuid = String(clLen, 0)
lRtn = StringFromGUID2(tGuid, VarPtr(bGuid(0)), clLen) 'use API to FORMat it
If lRtn > 0 Then 'truncate nulls
GuidToString = Mid$(bGuid, 1, lRtn - 1)
End If
End Function