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.
-
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
-
Close the Visual Basic Editor and save the form as NewCustomers.
- On the View menu, click Form View. Make a note of the value of the current CustomerID.
- On the Records menu, click Data Entry to add a new record.
- Enter the value of the earlier noted CustomerID.
The message box with your message appears and the cursor is returned to the CustomerID field.