1

I found the following VBscript function to generate a random code using Uppercase & Lowercase characters. I'd like to extend it to include digits - I tried by adding in the extra few lines (max3 and min3) , but am not sure how to change the Array to allow for the new variables.

Function GenerateRandomString(StrLen,upper,lower,numeric)
    Dim charCase
    ' ASCII: Lowercase Alpha Characters
    max=122
    min=97
    ' ASCII: Capital Alpha Characters
    max2=90
    min2=65

    //  THIS BELOW IS WHAT I ADDED:
    ' ASCII: numeric Characters
    max3=57
    min3=49
    // END ADD
    

    For i=0 To (StrLen-1)
        Randomize
        charCase = Array((max-min+1)*Rnd+min,(max2-min2+1)*Rnd+min2)   <!-- Not sure how to change this?
        myStr = myStr & Chr(int(charCase(int(Rnd*2))))
    Next
   
    GenerateRandomString = myStr
End Function   

1 Answer 1

2

The code creates an array with 2 values then picks one of those. The simplest solution is to add a third value to the array:

Randomize
For i=0 To (StrLen-1)
    charCase = Array((max - min + 1) * Rnd + min, _
                     (max2 - min2 + 1) * Rnd + min2, _
                     (max3 - min3 + 1) * Rnd + min3)
    myStr = myStr & Chr(int(charCase(int(Rnd * 3))))
Next

Another option is to create a string with the values you want and use that:

letters ="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz"
For i=0 To (StrLen-1)
    ' Pick a random letter from the string and add to the result
    myStr = myStr & Mid(letters, int(Rnd * Len(letters)) + 1, 1)
Next
Sign up to request clarification or add additional context in comments.

2 Comments

Using your second option, I sometimes receive this error: Invalid procedure call or argument: 'Mid' - referring to the line of myStr = myStr & Mid(letters, int(Rnd * Len(letters)), 1) . Any idea what that may be?
Sorry, int(Rnd * Len(letters)) will produce a number n where 0 <= n < Len(letters). In most languages this is what you want, but in VBA Mid requires 1 <= n <= Len(letters). So just add 1. I will update the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.