stanigator
stanigator

Reputation: 10944

vba more realistic random number generator

I know I can use a quasi-random number generation function/variable called Rnd. However, I've noticed that whenever I used Rnd in my userform, this sequence of numbers always show up:

first iteration: 0.705547511577606 second iteration: 0.533424019813538 ...

As a result, b/c the sequence of numbers showing up are the same every time when I relaunch the userform, it doesn't feel random. Are there other functions in the VBA function set that would make it feel more random? Thanks in advance.

Upvotes: 4

Views: 4871

Answers (3)

CalfordMath
CalfordMath

Reputation: 102

You could manually set the seed based on the time of day... insert something like this at the top of your vba code:

For i = 0 To (CInt(Format(Time, "ms"))) 'minutes and seconds turned to integer
        test_random = Rnd()
    Next

Upvotes: 0

Travis Beale
Travis Beale

Reputation: 5648

Try adding a single call to Randomize Timer before you do any calls to Rnd. This will seed the random number generator using the time of day.

Upvotes: 10

Luke
Luke

Reputation: 21296

I don't know a lot about VB but I think you need to seed your number generator. I think Randomize does it for VB.

Upvotes: 2

Related Questions