Return to VBA Code Examples

VBA Rnd Function

Written by

Editorial Team

Reviewed by

Steve Rynearson

Last updated on July 19, 2021

Rnd Function

Used to change the seed value used by the random number generator for the Rnd function.

Simple Rnd Examples

Sub Rnd_Example()
    Dim randomValue
    randomValue = Rnd
End Sub

Rnd Syntax

In the VBA Editor, you can type  “Rnd(” to see the syntax for the Rnd Function:

The Rnd function contains an argument:

Number: [Optional] Any valid numeric expression.

Examples of Excel VBA Rnd Function

To generate random integer value between 1 and 10, you can use the following code.

Sub Rnd_Example1()
    Dim rndValue As Single
    For i = 1 To 20
        rndValue = Int((Rnd * 10) + 1)
    Next i
End Sub

This code will generate 20 random integer value between 1 and 10.

To generate random value between an lower bound and an upper bound, you can use the following function.

Function RndSpecial(upperbound As Single, lowerbound As Single) As Single
    RndSpecial = (upperbound - lowerbound) * Rnd
End Function
Sub Rnd_Example2()
    Dim randomValue As Single
    randomValue = RndSpecial(5, 30)
    MsgBox randomValue
End Sub

This will return a random value between 5 and 30.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as

Learn More!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples