访问vba中的此代码未运行
Private Sub Command0_Click()
Dim pool As String
pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim count
count = 0
result.Text = ""
Randomize
Dim cc
cc As New Rnd
Dim strpos
strpos = ""
While count <= Lengthh.Text
strpos = cc.Next(0, pool.length)
result.Text = result.Text & pool(strpos)
count = count + 1
Wend
End Sub
答案 0 :(得分:1)
在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
End Function
像这样使用:
Sub test()
Randomize
MsgBox RandString(50)
End Sub
典型输出如下:
fvdDUV1csFLhzCmrvJtYx4wXr1QGqSai6yiGSC4ByzB53kG5E1
答案 1 :(得分:0)
扩展@John Coleman的答案。
此处,“匿名”功能将根据您的输入创建随机字符串或数字。如果传递字符串,则将返回字符串,如果传递数字,则将返回数字。请注意,返回值的长度将与您输入的值相同
Public Function Anonymise(str As String)
chunks = Split(str, " ")
Dim ret As String
ret = ""
If IsNumeric(str) = False Then
For i = 0 To UBound(chunks) - LBound(chunks)
ret = ret + " " + RandString(Len(chunks(i)))
Next i
ret = Trim(ret)
Anonymise = StrConv(ret, vbProperCase)
Else
For i = 0 To UBound(chunks) - LBound(chunks)
ret = ret + " " + RandNum(Len(chunks(i)))
Next i
ret = Trim(ret)
Anonymise = ret
End If
End Function
Function RandString(n As Long) As String
Dim i As Long, j As Long, m As Long, s As String, pool As String
pool = "abcdefghijklmnopqrstuvwxyz"
m = Len(pool)
For i = 1 To n
j = 1 + Int(m * Rnd())
s = s & Mid(pool, j, 1)
Next i
RandString = s
End Function
Function RandNum(n As Long) As String
Dim i As Long, j As Long, m As Long, s As String, pool As String
pool = "0123456789"
m = Len(pool)
For i = 1 To n
j = 1 + Int(m * Rnd())
s = s & Mid(pool, j, 1)
Next i
RandNum = s
End Function