TOP

VBA Function: Rnd

Description

The VBA Rnd function returns a random number less than 1 and greater than or equal to 0.


Rnd Syntax

Rnd

VBA Rnd Example

Some examples of values returned by the Rnd function:

Sub RndExample1()
    
      Randomize
    
      MsgBox Rnd 'Returns, for example: 0.1790262
      MsgBox Rnd 'Returns, for example: 0.734448
      MsgBox Rnd 'Returns, for example: 0.4870669
      MsgBox Rnd 'Returns, for example: 0.9100572
      MsgBox Rnd 'Returns, for example: 0.7860449
      MsgBox Rnd 'Returns, for example: 0.1607063
    
end sub
Always add a Randomize statement to your procedure or function before using the Rnd function to prevent repeating random numbers.

Generate a random integer from 1 to 10 using the Rnd function:

Function RandomNumber()
    
      Randomize
    
      RandomNumber = Int(Rnd * 10 + 1)
    
end function

Sub RndExample2()
    
      MsgBox RandomNumber 'Returns, for example: 6
      MsgBox RandomNumber 'Returns, for example: 2
      MsgBox RandomNumber 'Returns, for example: 10
      MsgBox RandomNumber 'Returns, for example: 7
      MsgBox RandomNumber 'Returns, for example: 9
      MsgBox RandomNumber 'Returns, for example: 1
      MsgBox RandomNumber 'Returns, for example: 8
    
end sub