752 Chapter 29
•
The heart of the program uses the function Int(draw * 10) + 1.
Multiplying the random draw by 10 produces a number whose fi rst digit
is 0, 1, . . . , or 9. The VBA function Int gives this integer. Distribution is
a VBA array numbered 1 to 10, with Distribution(1) being the number
of random numbers in [0, 0.1), Distribution(2) the number of random
numbers in [0.1, 0.2), etc. Thus Int(draw * 10) + 1 is the proper
place in Distribution to which the current random draw belongs.
29.3.1 Using Randomize to Produce the Same List (or Not) of Random
Numbers
Most random-number generators use the last generated “random”
number to produce the next.
6
The fi rst number used in a particular
sequence is controlled by the “seed,” which is typically taken from the
computer’s clock. VBA’s Rnd is no exception, but it allows you to control
the seed by using the command Randomize. The two small programs that
follow illustrate two uses of this command.
•
Using Randomize without any numeric argument resets the seed
(meaning that it breaks the connection between the next random number
and the current random number). This approach is illustrated in the
macro Random_EachDifferent, though it is diffi cult to see the effect.
Sub Random_EachDifferent()
‘Produces a list of random numbers
Randomize
‘Initializes the VBA random-number generator
For Index = 1 To 10
Range(“A5”).Cells(Index, 1) = Rnd()
Next Index
End Sub
•
Using Randomize(seed) uses a particular number as the seed.
•
Using the sequence of commands Rnd(negative number) and
Randomize(seed) guarantees the same sequence of random numbers.
This approach is illustrated in the macro Random_Same.
6. There are more examples in the exercises at the end of the chapter.