ACC: Macro to Check for Duplicate Values in a Field

ID: Q103135


The information in this article applies to:


SUMMARY

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

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:

  1. Open the Northwind.mdb (or NWIND.MDB in versions 1.x and 2.0).


  2. Create a new form based on the Customers table.


  3. 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.


  4. In Design view for the form, attach this macro to the AfterUpdate property of the CustomerID control.


  5. In Form view, make a note of the value of the current CustomerID.


  6. On the Records menu, click Data Entry to add a new record.


  7. 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.



REFERENCES

For more information about duplicate values in a field, search the Help Index for "duplicate values," or ask the Microsoft Access 97 Office Assistant.

Additional query words: validate same validationrule


Keywords          : kbusage McrCond 
Version           : 1.0 1.1 2.0 7.0 97
Platform          : WINDOWS 
Issue type        : kbinfo 

Last Reviewed: March 25, 1999