VBA Tip: Random Number Generator


You can use the following code to generate a random number between 1 and 50:

Sub random_num()

    'Initialize the random number generator
    '=> Randomize: add this before you call the Rnd function to obtain completely random values
    Randomize
   
    'Random whole number between 1 and 50:
    random_number = Int(50 * Rnd) + 1
   
    MsgBox random_number
   
End Sub

To get a random number between 1 and 22, for example, simply replace 50 (in the above code) with 22.