VBA Random Number

Written by

Editorial Team

Reviewed by

Steve Rynearson

Last updated on September 21, 2021

This tutorial will demonstrate how to work with random numbers in VBA.

RND Function

The RND Function generates a number that is between 0 and 1. The syntax of the RND Function is:

Rnd([Number]) where:

  • Number (Optional) – This is optional and if <0, the function returns the same random number on each call using [Number] as the seed, if =0, the function returns the most recent random number, if >0 the function returns the next generated random number. If blank the default >0, is used.
Sub RndNum()
    MsgBox Rnd()
End Sub

Generating a Random Number in VBA

In order to generate a random number between two values, you have to use the RND Function in combination with the INT Function  (Integer Function) using the following general formula:

  • Int(lowerbound + Rnd * ( upperbound – lowerbound + 1 ) )

So, in order to generate a random number between 2 and 30, you would use the following code:

Sub GeneratingARandomNumber()

Dim randomNumber As Integer

randomNumber = Int(2 + Rnd * (30 - 2 + 1))
Debug.Print randomNumber

End Sub

 

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-free-addin

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