Name
Randomize Sub
Syntax
Randomize [number
]
number
Use: Optional
Data Type: Numeric
Any valid numeric expression.
Description
Initializes the random number generator.
Rules at a Glance
Randomize
usesnumber
as a new seed value to initialize the random number generator used by theRnd
function. The seed value is an initial value that generates a sequence of pseudorandom numbers.If you don’t pass
number
to theRandomize
statement, the value of the system timer is used as the new seed value.Repeatedly passing the same number to
Randomize
doesn’t causeRnd
to repeat the same sequence of random numbers.If
Randomize
is not used and theRnd
function is called either with no argument or with 1 as an argument, the Rnd function always uses the same number as the seed value the first time it is called, and subsequently uses the last generated number as a seed value.
Programming Tips and Gotchas
If you need to repeat a sequence of random numbers, you should
call the Rnd
function with a
negative number as an argument immediately prior to using Randomize
with any numeric argument. This
is illustrated in the example program.
Example
RepeatNumbers() Sub RepeatNumbers() Dim arr(9, 3) Dim loopCtr, intCtr Dim strMsg For loopCtr = 0 To 3 Rnd -1 Randomize(100) For intCtr = 0 To 9 strMsg = strMsg & Rnd() & " " Next strMsg = strMsg & vbCrLf Next MsgBox strMsg End Sub
See Also
Get VBScript in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.