VBA Tip: Generate Random Numbers


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

Sub randomNum()

    '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:
    randomNumber = Int(50 * Rnd) + 1
    
    MsgBox randomNumber
    
End Sub

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