Microsoft KB Archive/209479

= ACC2000: How to Use Visual Basic for Applications to Check for Duplicate Values in a Field =

Article ID: 209479

Article Last Modified on 10/11/2006

-

APPLIES TO


 * Microsoft Access 2000 Standard Edition

-



This article was previously published under Q209479



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
This article demonstrates how to create a Visual Basic for Applications procedure that uses the DLookup function to check for duplicate values in a field before you leave that 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 code will perform a duplicate check as the data is entered in a field. To check for duplicate values in a field as you enter the data, follow these steps:

CAUTION: If you follow the steps in this example, you modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and follow these steps on a copy of the database.

 Start Microsoft Access and open the sample database Northwind.mdb. In the Database window, click Forms under Objects, and then click New. In the New Form dialog box, click Auto: Columnar and then select Customers to indicate the table where the form's data comes from. View the form in Design view, and click the CustomerID text box. If the property sheet is not already visible, click Properties on the View menu. In the Before Update event, select [Event Procedure] to run just before you update the data in the CustomerID field.</li>  On the View menu, click Code. Type or paste in the following code: Private Sub CustomerID_BeforeUpdate(Cancel As Integer)

Dim x As Variant

x = DLookup("[CustomerID]", "Customers", "[CustomerID]= '" _    & Forms!newcustomers!CustomerID & "'")

On Error GoTo CustID_Err

If Not IsNull(x) Then Beep MsgBox "That value already exists", vbOKOnly, "Duplicate Value" Cancel = True End If

CustID_Exit: Exit Sub

CustID_Err: MsgBox Error$ Resume CustID_Exit End Sub </li> Close the Visual Basic Editor and save the form as NewCustomers .</li> On the View menu, click Form View. Make a note of the value of the current CustomerID.</li> 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 appears and the cursor is returned to the CustomerID field.</li></ol>

<div class="references_section">