'How to generate a string of random characters from a given list of characters?

How can I generate a string of random characters from a given list of characters?

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


Solution 1:[1]

Extending @John Coleman's answer.

Here the "Anonymise" function will create a random string or number based on your input. If you pass a string, it will return a string, if you pass a number, it will return a number. Note that the length of the return value will be the same as your input value

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

Solution 2:[2]

For those wanting speed, you would want to avoid string concatenation with &. Concatenation can be done much faster with an array of characters and Join(), as documented in the answer to this question.

The function below skips Join() and uses byte arrays for an additional speed boost (for more on that, see this answer).

Function RandStringFromPool(stringLength As Long, charPool As String) As String

    Randomize
    Dim returnByteArray() As Byte
    Dim poolByteArray() As Byte: poolByteArray = StrConv(charPool, vbFromUnicode)
    Dim poolSize As Long: poolSize = Len(charPool)
    
    ReDim returnByteArray(0 To stringLength * 2 - 1)
    For i = 0 To UBound(returnByteArray) Step 2
        returnByteArray(i) = poolByteArray(Int(Rnd() * poolSize))
    Next
    RandStringFromPool = returnByteArray
    
End Function

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nesar
Solution 2 Mark E.