Excel VBA Rnd Function
VBA Rnd Function: The Rnd function in VBA returns a random number that is greater than or equal to (>=) 0 and is less than (<) 1.
Syntax
Rnd ([Number])
Parameter
Number (optional) –This parameter represents a numeric value.
It can take the following values:
< 0 (greater than 0) – It signifies the same random number on each call as the seed Number
= 0 (equal to 0) – It signifies the recently generated random number.
>0 (less than 0) - It signifies the next random number in the sequence
Return
This function returns a random number that is greater than or equal to (>=) 0 and is less than (<) 1.
Example 1
Sub RndFunction_Example1() ' will return different random numbers between 0 and 1. Dim rnd_val1 As Double Dim rnd_val2 As Double Dim rnd_val3 As Double ' Initializing the random number generator. Randomize rnd_val1 = Rnd() ' The variable rand1 is now equal to 0.280329287052155. Cells(1, 1).Value = rnd_val1 rnd_val2 = Rnd() ' The variable rand2 is now equal to 0.914913654327392 Cells(2, 1).Value = rnd_val2 rnd_val3 = Rnd() ' The variable rand3 is now equal to 0.492544829845428 Cells(3, 1).Value = rnd_val3 End Sub
Output
0.280329287 |
0.914913654 |
4.93E-01 |
Example 2
Sub RndFunction_Example2() ' will return different random numbers between 0 and 1. Dim rnd_val1 As Double Dim rnd_val2 As Double ' Initializing the random number generator. Randomize rnd_val1 = Rnd(-21) ' The variable rand1 is now equal to 0.733894348144531. Cells(1, 1).Value = rnd_val1 rnd_val2 = Rnd(21) ' The variable rand2 is now equal to 0.695270717144012. Cells(2, 1).Value = rnd_val2 End Sub
Output
0.733894348144531
0.695270717144012