February 5, 2009

Generating Random Characters and Strings

Filed under: Scripting — Marcus Tettmar @ 1:10 pm

Macro Scheduler has a Random function which will give you a random number between a specified range. Every now and then I am asked how you can create a random character or random character string.

The solution is to use VBScript’s Chr function which returns the character for the specified Ascii code. So we can use Random to get a random number within the required Ascii range, and then use Chr to get the corresponding character. There are a few examples in the forums, such as this one.

I was recently asked how to generate a random character from A to Z. Here’s my response:

Look at the ASCII table: http://www.asciitable.com/

Let’s look at upper case only first:

A is ascii code decimal 65
Z is ascii code decimal 90

So if we want a random character from A-Z inclusive we want to get a random number in that range (65 to 90).

Clearly it’s a range of 26. Random gives a value from 0 to range-1. So:

Random>26,random_number

So to get that into our range we clearly need to add it to 65, because the ascii range begins at 65 for “A”:

Let>ascii_code=65+random_number

Now we have an ascii code in the required range. So now use VBScript’s Chr function which returns the corresponding character for the ascii code:

VBEval>chr(%ascii_code%),random_char

So, in long form:

Random>26,random_number
Let>ascii_code=65+random_number
VBEval>chr(%ascii_code%),random_char

Or, shorter version:

Random>26,random_number
VBEval>chr(%random_number%+65),random_char

That will give you a random character between A and Z inclusive.

If you want lower case then the range is 97 – 122. There are some characters in between. So if you want to mix lower case and upper case, you could either look at the entire range, discarding any results that appear between the two, or throw a coin (Random>2) to determine whether to do the upper case range or the lower case range, or, I think simpler, randomly convert to lower case, e.g.:

Random>26,random_number
VBEval>chr(%random_number%+65),random_char

Random>2,UpperOrLower
If>UpperOrLower=0
  VBEval>LCase("%random_char%"),random_char
Endif

MessageModal>random_char

Remember, to use VBScript you need a VBSTART/VBEND block in your script, even if it is empty. Stick it at the top. So the whole example script becomes:

VBSTART
VBEND

Random>26,random_number
VBEval>chr(%random_number%+65),random_char

Random>2,UpperOrLower
If>UpperOrLower=0
  VBEval>LCase("%random_char%"),random_char
Endif

MessageModal>random_char