如何从给定的字符列表生成一串随机字符?

Had*_*zad 0 ms-access 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
Run Code Online (Sandbox Code Playgroud)

Joh*_*man 5

在 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
Run Code Online (Sandbox Code Playgroud)

像这样使用:

Sub test()
    Randomize
    MsgBox RandString(50)
End Sub
Run Code Online (Sandbox Code Playgroud)

典型的输出如下所示:

fvdDUV1csFLhzCmrvJtYx4wXr1QGqSai6yiGSC4ByzB53kG5E1
Run Code Online (Sandbox Code Playgroud)