Saturday, September 11, 2010

The Password Function

I've worked with a lot of customers who have to generate random passwords for their users to log on to one kind of system or another.

I've seen algorithms and programs to do it; I thought recently, "What if I could write a function to do that in Excel?" I've done some ham-handed functions to make it happen (using RAND() and MID() and repeating the function eight times), but I was thinking there has to me a more elegant way.

I think I finally have it:

Public Function PasswordGen(Optional PasswordLength As Byte)
If PasswordLength = 0 Then
PasswordLength = 8
End If
Dim g As Byte
For g = 1 To PasswordLength
PasswordGen = PasswordGen & Chr(Rnd * (122 - 36 + 1) + 36)
Next g
End Function


In short, the optional PasswordLength argument allows the user to specify how many characters they want the password to be; eight is the default, but if you need sixteen, I have you covered.

Once that's been established, it's just a loop from one to the argument's length; just keep picking a random number between 122 and 36, and then get the ASCII character value that corresponds to that numeric position. 36 is the starting position on the ASCII character list of usable characters; 122 is the outer limit.

Simple function, I grant you, but useful. If you can use it, please do. I'll have more functions and useful stuff later, but until then, be well.