BeforeUpdate, AfterUpdate Events — Event Procedures Example

The following example shows how you can use a BeforeUpdate event procedure to check whether a product name has already been entered in the database. After the user types a product name in the ProductName box, the value is compared to the ProductName field in the Products table. If there is a matching value in the Products table, a message is displayed that informs the user that the product has already been entered.

To try the example, add the following event procedure to a form named Products that contains a text box called ProductName.

Private Sub ProductName_BeforeUpdate(Cancel As Integer)
    If(Not IsNull(DLookup("[ProductName]", _
        "Products", "[ProductName] ='" _
        & Me!ProductName & "'"))) Then
        MsgBox "Product has already been entered in the database."
        Cancel = True
        Me!ProductName.Undo
    End If
End Sub