我正在VBA上(不是专家)在MS-Visio 2010下工作,我想基于作为种子的字符串生成一个随机数(甚至更好)。
我知道Rnd(seed)
的种子为负数exists。但是,我不知道任何带有字符串作为种子的随机生成器。也许某种哈希函数的结果是数字?
我想要类似的东西:
print function("abc")
45
print function("xyz abc-5")
86
print function("abc")
45
在种子字符串中时带有空格,符号和数字的支持。
我可能会看到一种解决方法,可以将每个字符转换为对应的某个ascii编号,并以某种方式将这个大数字用作Rnd的种子,但是绝对觉得牵强。有人知道这样做的更好方法吗?
答案 0 :(得分:1)
结合了这些例子
收件人:
Function hash4(txt)
' copied from the example
Dim x As Long
Dim mask, i, j, nC, crc As Integer
Dim c As String
crc = &HFFFF
For nC = 1 To Len(txt)
j = Asc(Mid(txt, nC)) ' <<<<<<< new line of code - makes all the difference
' instead of j = Val("&H" + Mid(txt, nC, 2))
crc = crc Xor j
For j = 1 To 8
mask = 0
If crc / 2 <> Int(crc / 2) Then mask = &HA001
crc = Int(crc / 2) And &H7FFF: crc = crc Xor mask
Next j
Next nC
c = Hex$(crc)
' <<<<< new section: make sure returned string is always 4 characters long >>>>>
' pad to always have length 4:
While Len(c) < 4
c = "0" & c
Wend
Dim Hex2Dbl As Double
Hex2Dbl = CDbl("&h0" & c) ' Overflow Error if more than 2 ^ 64
If Hex2Dbl < 0 Then Hex2Dbl = Hex2Dbl + 4294967296# ' 16 ^ 8 = 4294967296
hash4 = Hex2Dbl
End Function
立即尝试(在VBA编辑器窗口中为Ctrl
+ G
)
?hash4("Value 1")
31335
?hash4("Value 2")
31527
此功能将:
答案 1 :(得分:0)
在VBA中,Rnd
是一个函数,而不是类,并且字符串不能被视为数组。您需要使用函数Mid
提取单个字符。
您可以编写函数以返回随机字符串。然后,事件处理程序可以使用该函数:
Function RandString(n As Long) As String
'Assumes that Randomize has been invoked by caller
Dim i As Long, j As Long, m As Long, s As String, pool As String
pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
m = Len(pool)
For i = 1 To n
j = 1 + Int(m * Rnd())
s = s & Mid(pool, j, 1)
Next i
RandString = s
RandString = Asc(RandString)
End Function
Sub test()
Randomize
MsgBox RandString(50)
End Sub
典型输出如下:
fvdDUV1csFLhzCmrvJtYx4wXr1QGqSai6yiGSC4ByzB53kG5E1
然后将您的字符串转换为数字:
Asc(myString)
因此该示例的输出为:102
希望这对您有帮助
注意::您可以将所有想要的字符添加到池中(例如:“-”或“”)