Microsoft KB Archive/304085

= ACC2002: How to Generate Random Dates =

Article ID: 304085

Article Last Modified on 6/23/2005

-

APPLIES TO


 * Microsoft Access 2002 Standard Edition

-



This article was previously published under Q304085



Moderate: Requires basic macro, coding, and interoperability skills.

This article applies to a Microsoft Access database (.mdb) and to a Microsoft Access project (.adp).



SUMMARY
By using the Rnd function in Visual Basic for Applications (VBA), you can generate a random date value. This may be useful for generating sample data for your application or for testing values. This article shows you two functions that you can use to generate random dates.



MORE INFORMATION
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.

The two functions included are:
 * RandomDateInRange Generates a random date within a specified range.
 * RandomDate Generates a random date between December 30, 1899 and the current date.

Sample Code
 Start Microsoft Access, and then open the database that you are working with. Click Modules under Objects, and then click New to insert a new module.  Type or paste the following code in the module: Function RandomDateInRange(LowerDate As Date, UpperDate As Date) As Date RandomDateInRange = Int((UpperDate - LowerDate + 1) * Rnd + LowerDate) End Function

Function RandomDate As Date ' multiply the Rnd function * date + 1 to prevent dates ' in the future RandomDate = Int(Rnd * CDbl(Date + 1)) End Function  On the File menu, click Save  to save the module, where  is the name of your Visual Basic for Applications project.  Type the following lines in the Immediate window, and press ENTER after each line: ? RandomDateInRange(#1/1/2001#, #12/31/2001#) ? RandomDate </li></ol>

<div class="references_section">