MS Access: Rnd Function

This MSAccess tutorial explains how to use the Access Rnd function with syntax and examples.

Description

The Microsoft Access Rnd function allows you to generate a random number (integer value). You can specify the random number to be a value between 2 user-specified numbers.

Syntax

The syntax for the Rnd function in MS Access is:

`Int ((upperbound - lowerbound + 1) * Rnd + lowerbound)`

Parameters or Arguments

upperbound
The highest value that the random number can be.
lowerbound
The lowest value that the random number can be.

Applies To

The Rnd function can be used in the following versions of Microsoft Access:

• Access 2013, Access 2010, Access 2007, Access 2003, Access XP, Access 2000

Example

Let's look at how to use the Rnd function in MS Access:

```Int ((6 - 1 + 1) * Rnd + 1)
Result: random number between 1 and 6

Int ((200 - 150 + 1) * Rnd + 150)
Result: random number between 150 and 200

Int ((999 - 100 + 1) * Rnd + 100)
Result: random number between 100 and 999```

Example in VBA Code

The Rnd function can be used in VBA code in Microsoft Access.

For example:

```Dim LRandomNumber As Integer

LRandomNumber = Int ((300 - 200 + 1) * Rnd + 200)```

In this example, the variable called LRandomNumber would now contain a random number between 200 and 300.

If you find that you are not getting a truly random number when calling the Rnd function, you can use the Randomize function to change the seed value for the Rnd function's random number generator. The call to the Randomize function should preceed the call to the Rnd function.

For example,

```'Example provided by techonthenet.com

Dim LRandomNumber As Integer

Randomize
LRandomNumber = Int ((300 - 200 + 1) * Rnd + 200)```

In this example, the variable called LRandomNumber would now contain a random number between 200 and 300. The Randomize function would ensure that the number generated is truly random by initializing the random number generator with a seed value that is equivalent to the system timer.

Warning: If you don't call the Randomize function before calling the Rnd function, the Rnd function may return the same random number value each time. And therefore, you may not get a truly random number.

Example in SQL/Queries

You can also use the Rnd function in a query in Microsoft Access.

For example:

In this query, we have used the Rnd function as follows:

`Expr1: Int((300-200+1)*Rnd()+200)`

This query will return the results in a column called Expr1. You can replace Expr1 with a column name that is more meaningful.

For example:

`CalcValue: Int((300-200+1)*Rnd()+200)`

The results would now be displayed in a column called CalcValue.

Share: