Excel

Generating Random Numbers

Ease of Use

Easy

Version tested with

2002 

Submitted by:

Jacob Hilderbrand

Description:

This is a method for generating a random number between any two values. 

Discussion:

Random numbers can be used for a lot of things. For example, you may want to calculate a dice roll, with results between 1 and 6. Or a Kino number from 1 to 80. 

Code:

instructions for use

			

Option Explicit Public Function RandomNumber(Lowest As Long, Highest As Long) Application.Volatile Randomize RandomNumber = Int((Highest + 1 - Lowest) * Rnd + Lowest) End Function

How to use:

  1. Open your workbook.
  2. Hit Alt + F11 to open the Visual Basic Editor.
  3. From the menu, choose Insert -Module.
  4. Paste the code into the window at right.
  5. Close VBE (Alt + Q or press the X in the top right hand corner).
 

Test the code:

  1. In any cell type: =randomnumber(1,80) to get a result between 1 and 80; change the 1 and the 80 as desired. To run this from another procedure: x = RandomNumber(1, 80), and x will hold the random number value as a variable you can use in further calculations.
 

Sample File:

RandomNumber.ZIP 6.06KB 

Approved by mdmackillop


This entry has been viewed 258 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express