BeforeInsert Event [Access 2003 VBA Language Reference]
The BeforeInsert event occurs when the user types the first character in a new record, but before the record is actually created.
Private Sub Form_BeforeInsert(Cancel As Integer)**
Cancel The setting determines if the BeforeInsert event occurs. Setting the Cancel argument to True (–1) cancels the BeforeInsert event.
Note Setting the value of a control by using a macro or Visual Basic doesn't trigger these events.
To run a macro or event procedure when these events occur, set the BeforeInsert or AfterInsert property to the name of the macro or to [Event Procedure].
You can use an AfterInsert event procedure or macro to requery a recordset whenever a new record is added.
BeforeInsert → BeforeUpdate → AfterUpdate → AfterInsert.
The following table summarizes the interaction between these events.
|BeforeInsert||User types the first character in a new record.|
|BeforeUpdate||User updates the record.|
|AfterUpdate||Record is updated.|
|AfterInsert||Record updated is a new record.|
If the first character in a new record is typed into a text box or combo box, the BeforeInsert event occurs before the Change event.
You can use these macros to display messages or useful information. For example, you can have the BeforeInsert macro display data the user needs when entering a new record.
You can use the CancelEvent action in a BeforeInsert macro to cancel the creation of the new record. When you use the CancelEvent action in a BeforeInsert macro, the focus returns to the new record, which is blank (the character that the user typed is deleted).
You can't use the CancelEvent action in an AfterInsert macro.
This example shows how you can use a BeforeInsert event procedure to verify that the user wants to create a new record, and an AfterInsert event procedure to requery the record source for the Employees form after a record has been added.
To try the example, add the following event procedure to a form named Employees that is based on a table or query. Switch to form Datasheet view and try to insert a record.
Private Sub Form_BeforeInsert(Cancel As Integer) If MsgBox("Insert new record here?", _ vbOKCancel) = vbCancel Then Cancel = True End If End Sub Private Sub Form_AfterInsert() Forms!Employees.Requery End Sub
Applies to | Form Object