Saturday, January 12, 2013

Random Number Generator with VBA

Ever wanted to generate a number with a range? Here is the code snippet to do it!
Function GenerateRandomNumber(LowerNumber As Integer, UpperNumber As Integer) As Integer
Randomize
GenerateRandomNumber = Int((UpperNumber - LowerNumber + 1) * Rnd + LowerNumber)
End Function
To use this function, simply paste the method in a module and call that method when assigning a variable a random number.

Here is an example to assign x to a random number between 1 to 10
Function GenerateRandomNumber()....

Sub PrintRandomNumber()
Dim x As Integer
x = GenerateRandomNumber(1, 10)
End Sub

No comments: