Making Excel/VBA random numbers more random with a seed
I have a fairly simple user-defined function for Excel that I use to create random passwords. (I got kind of freaked out last year after someone hacked into my Facebook account. Trouble was, I used the same password for lots of sites. If this petty crook had been a little more savvy, he could have done a lot more damage. At first, I immediately replaced a bunch of my passwords with strings like this: p9q4MF3nnX4B. The only problem now is that I can’t remember any of my passwords, and have to keep them in a file, which creates security concerns of its own…)
I noticed that my little password routine would repeatedly create the same password each time I used it anew, after re-starting the computer and re-launching Excel. It turns out that VBA’s RAND function is not as random as you’d think it might be. The way around this is
I saw this code that I found on the techguy forum:
seed = TimeValue("00:" & Format(Second(Time), "00") & ":" & Format(Minute(Time), "00"))
Randomize (seed)
But according to the RND entry at the support site, you can just call Randomize on its own:
Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.
I had never used Randomize before, and never knew that I needed to. In Python, a more sophisticated programming language, seeding is taken care of for you: “current system time is also used to initialize the generator when the module is first imported.”
Lots more information at the Wikipedia article on Pseudo-Random Number Generators. From here I learned, “A PRNG can be started from an arbitrary starting state using a seed state. It will always produce the same sequence thereafter when initialized with that state.”
