get random characters from inserted string in excel vba code example

Example: select random 4 character from string in excel vba

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

Tags:

Misc Example