有什么方法可以在代码中生成唯一的数字? 我有一个使用系统时间的想法,但最终无法实现它。
答案 0 :(得分:2)
您可以使用Now()然后将输出格式化为数字。
Sub unique()
Dim t As Date
t = Now()
Range("A1").NumberFormat = "@"
Range("A1") = CStr(Format(t, "yyyymmddhhMMss"))
End Sub
这将是独特的。
正如@Vasily指出的那样,没有将单元格格式化为字符串并将数字作为sting放置,该值将被截断为科学记数法。
答案 1 :(得分:0)
特别是对于这种情况,发明了GUID(全球唯一标识符)。它可能有点过大......但只是你已经看到它了:
Option Explicit
Public Type TYP_GUID
bytes(15) As Byte
End Type
Public Declare Function CoCreateGuid Lib "OLE32.dll" _
(guid As TYP_GUID) As Long
Public Function newGUID() As TYP_GUID
Dim uGUID As TYP_GUID
CoCreateGuid uGUID
newGUID = uGUID
End Function
每当你调用newGUID()时,你将成为一个在世界上真正独一无二的价值。您可以尝试随意调用它......您将永远不会再次获得相同的值。
也可以将这样的GUID转换为字符串:
Option Explicit
Public Type TYP_GUID
bytes(15) As Byte
End Type
Public Declare Function CoCreateGuid Lib "OLE32.dll" _
(guid As TYP_GUID) As Long
Public Declare Function StringFromGUID2 Lib "OLE32.dll" _
(guid As TYP_GUID, _
ByVal lpszString As String, _
ByVal iMax As Long) As Long
Public Function newGUID() As TYP_GUID
Dim uGUID As TYP_GUID
CoCreateGuid uGUID
newGUID = uGUID
End Function
Public Function newGUID_String() As String
Dim sBuffer As String
Dim lResult As Long
sBuffer = VBA.Space(78)
lResult = StringFromGUID2(newGUID, sBuffer, Len(sBuffer))
newGUID_String = Left$(StrConv(sBuffer, vbFromUnicode), lResult - 1)
End Function