Microsoft KB Archive/103135

= ACC: Macro to Check for Duplicate Values in a Field =

Article ID: 103135

Article Last Modified on 1/18/2007

-

APPLIES TO


 * Microsoft Access 1.0 Standard Edition
 * Microsoft Access 1.1 Standard Edition
 * Microsoft Access 2.0 Standard Edition
 * Microsoft Access 95 Standard Edition
 * Microsoft Access 97 Standard Edition

-



This article was previously published under Q103135



Novice: Requires knowledge of the user interface on single-user computers.



SUMMARY
This article demonstrates how to create a macro that uses the DLookup function to check for duplicate values in a field.



MORE INFORMATION
Microsoft Access provides automatic checking for duplicate values in a field that has been designated as the primary key. However, this check occurs after all fields for a record have been entered, just before the record is committed to the database. The following sample macro is based on the sample database Northwind.mdb (or NWIND.MDB in versions 1.x and 2.0) and will perform a duplicate check as the data is entered in a field:

 Open the Northwind.mdb (or NWIND.MDB in versions 1.x and 2.0). Create a new form based on the Customers table.  Create a new macro as follows.

NOTE: In the following example, an underscore (_) is used as a line- continuation character. Remove the underscore from the end of the line when re-creating the example.

     Macro Name     Condition     Action --     MyMacro        1. MsgBox ...          SendKeys

1. DLookup("[CustomerID]", "Customers", "[CustomerID] = _           Form.[CustomerID]") is Not Null

NOTE: In versions 1.x and 2.0, there is a space in Customer ID.

MyMacro Actions --     MsgBox Message: That value already exists.

SendKeys Keystrokes: +{TAB} Wait: No Note that the ellipsis (...) under the condition indicates that the condition controls both macro actions. The SendKeys action will return the pointer to the field just exited.  In Design view for the form, attach this macro to the AfterUpdate property of the CustomerID control. In Form view, make a note of the value of the current CustomerID. On the Records menu, click Data Entry to add a new record.</li> Enter the value of the earlier noted CustomerID. The message box with your message will appear and the pointer will be returned to the CustomerID field.</li></ol>

<div class="references_section">