Tuesday, October 5, 2010

Generate a random alphabet string using VBScript

Usage Example:

MsgBox getRandomString(15)
' This would return a random string of 15 characters.

-------------------------------------------------------------

Public Function getRandomString(ofLength)
'********************************************
' Author : Chinmay Mudholkar
' Purpose : Getting a random alphabet string of a specified length
' Inputs : ofLength: The length of the random string required
' Returns : A random string of the specified length
'********************************************

If Not IsNumeric(ofLength) Or IsEmpty(ofLength) Or ofLength = "" Then
getRandomString = ""
Exit Function
End If

Dim retval, i
retval = ""
For i = 1 To ofLength
retval = retval & Chr(Int(26*Rnd+97))
Next
getRandomString = retval
End Function

-------------------------------------------------------------

1 comment:

  1. It's important to call the Randomize function before your first call to Rnd otherwise you'll have the same first letter every time.

    ReplyDelete