How can I use randomize and rnd to get a repeating list of random variables?
By repeating list, I mean if you run a loop to get 10 random numbers, each random number in the list will be unique. In addition, if you were to run this sequence again, you would get the same 10 random numbers as before.
From Microsoft’s own mouth:
See here for details.
The whole section:
Remarks
The
Rndfunction returns a value less than 1 but greater than or equal to zero.The value of number determines how
Rndgenerates a random number:For any given initial seed, the same number sequence is generated because each successive call to the
Rndfunction uses the previous number as a seed for the next number in the sequence.Before calling
Rnd, use theRandomizestatement without an argument to initialize the random-number generator with a seed based on the system timer.To produce random integers in a given range, use this formula:
Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.
Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using
Randomizewith a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.By way of example, if you put this code into Excel, it generates a different number each time you run it:
However, if you uncomment the
x = Rnd(-1)line, it generates the same number on each run.Note that you have to do two things. Call
Rndwith a negative argument and callRandomizewith a specific argument. Changing either of those things will give you a different seed (and therefore sequence).Edit:
Re your comment:
You now need one more piece of information. What you’re asking for is not random numbers but a shuffling algorithm. I’ll refer you to an earlier answer I gave on how to do this here. All you need to do is combine the shuffling algorithm with the seed-setting detailed above and you’ll have your repeatable, unique sequence.
And here’s some code that shows it in action. Every run of this subroutine returns the sequence
4 1 5 6 2 3 7 10 9 8so I think that’s what you were after, a repetable, “random”, unique sequence. If you wanted to be able to generate different sequences (but still in a repeatable manner), you only need to change the value given toRandomize.