Randomize Statement
Re-initializes the random-number generator with a new seed value.
Syntax
Randomize [number]
Arguments
| Part | Optional / Required | Description |
|---|---|---|
| number | Optional | A Variant or any valid numeric expression that is used as the new seed value to initialize the random number generator. |
Remarks
- The Randomize statement initializes the random-number generator, giving it a new seed value.
- If you omit number, the value returned by the system timer is used as the new seed value.
- If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.
- To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument.
- Using Randomize with the same value for number does not repeat the previous sequence.
Implementation
This follows the VB6 runtime internals (rtRandomize and rtRandomizeValue
in msvbvm60.dll), as preserved in .NET's VBMath.Randomize overloads, which
are explicitly documented as equivalent to those two functions.
Both forms take a value, XOR its low and high 16-bit halves, shift the
result up 8 bits, and splice that into the middle 16 bits of the current
seed while keeping the seed's top and bottom bytes. Because the low byte of
the previous seed is preserved, re-randomizing with the same value does not
repeat a sequence.
- Omitted argument — the value is Single seconds since midnight
(VB6 GetTimer), matching rtRandomize.
- Numeric argument — the high 32 bits of the argument's Double
representation are used, matching rtRandomizeValue.
The spliced seed is stored as-is (it can exceed 24 bits); Rnd keeps the
sequence 24-bit by masking when it advances.
Examples
' Initialize random number generator
Randomize
x = Int((100 * Rnd) + 1)
' Initialize with specific seed
Randomize 42
x = Rnd
' Use timer as seed
Randomize Timer