Alison Balteramp;#039;s Mastering Microsoft Office Access 1002003 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Alison Balteramp;#039;s Mastering Microsoft Office Access 1002003 [Electronic resources] - نسخه متنی

Alison Balter

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید



What Are the Form Events, and When Do You Use Them?


Microsoft Access

traps (responds to) for 31 Form events (excluding those specifically related to Pivot Tables), each of which has a distinct purpose. Access also traps events for Form sections and controls. The following sections cover the Form events and when you should use them.

Current


A form's Current event is one of the more commonly coded events. It happens each time focus moves from one record to another. The Current event is a great place to put code that you want to execute whenever the user displays a record. For example, you might want the cursor to move to the contact first name control if the user moves to a new client. The following code is placed in the Current event of the frmClients form that's part of the hypothetical time and billing application that we've been building in the previous chapters:

Private Sub Form_Current()
'If user is on a new record,
'move the focus to the Contact First Name control
If Me.NewRecord Then
Me.txtContactFirstName.SetFocus
End If
End Sub

This code moves focus to the txtContactFirstName control if the txtClientID control of the record that the user is moving to happens to be Null; this happens if the user is adding a new record.

BeforeInsert


The BeforeInsert event occurs when the first character is typed in a new record, but before the new record is actually created. If the user is typing in a text or combo box, the BeforeInsert event occurs even before the Change event of the text or combo box. The frmProjects form of the time and billing application has an example of a practical use of the BeforeInsert event:

Private Sub Form_BeforeInsert(Cancel As Integer)
On Error GoTo Err_Form_BeforeInsert
'Set the ClientID to the ClientID on the Clients form
Me.ClientID = Forms.frmClients.txtClientID
Exit_Form_BeforeInsert:
Exit Sub
Err_Form_BeforeInsert:
MsgBox Err.Description
Resume Exit_Form_BeforeInsert
End Sub

The frmProjects form is always called from the frmClients form. The BeforeInsert event of frmProjects sets the value of the txtClientID text box equal to the value of the txtClientID text box on frmClients.

AfterInsert


The AfterInsert event occurs after the record has actually been inserted. You can use it to re-query a recordset when a new record is added.

NOTE

Here's the order of form events when a user begins to type data into a new record:

BeforeInsert->BeforeUpdate->AfterUpdate->AfterInsert

The BeforeInsert event occurs when the user types the first character, the BeforeUpdate event happens when the user updates the record, the AfterUpdate event takes place when the record is updated, and the AfterInsert event occurs when the record that's being updated is a new record.

BeforeUpdate


The BeforeUpdate event runs before a record is updated. It occurs when the user tries to move to a different record (even a record on a subform) or when the Records, Save Record command is executed. You can use the BeforeUpdate event to cancel the update process when you want to perform complex validations. When a user adds a record, the BeforeUpdate event occurs after the BeforeInsert event. The frmClients form in the Chap9Ex sample database provides an example of using a BeforeUpdate event:

Private Sub Form_BeforeUpdate(Cancel As Integer)
'If the Contact FirstName, LastName, Company, or
'Phone Number is left blank, display a message
'and cancel the update
If IsNull(Me.txtContactFirstName) Or _
IsNull(Me.txtContactLastName) Or _
IsNull(Me.txtCompanyName) Or _
IsNull(Me.txtPhoneNumber) Then
MsgBox "The Contact First Name, " & vbCrLf & _
"Contact Last Name, " & vbCrLf & _
"Company Name, " & vbCrLf & _
"And Contact Phone Must All Be Entered", _
vbCritical, _
"Canceling Update"
Me.txtContactFirstName.SetFocus
Cancel = True
End If
End Sub

This code determines whether the first name, last name, company name, or phone number contains Nulls. If any of these fields contains Null, the code displays a message, and the Cancel parameter is set to True, canceling the update process. As a convenience to the user, focus is placed in the txtFirstName control.

AfterUpdate


The AfterUpdate event occurs after the changed data in a record is updated. You might use this event to re-query combo boxes on related forms or perhaps to log record changes. Here's an example:

Private Sub Form_AfterUpdate()
Me.cboSelectProduct.Requery
End Sub

This code re-queries the cboSelectProduct combo box after the user updates the current record.

Dirty


The Dirty event occurs when the contents of the form, or of the text portion of a combo box, change. It also occurs when you programmatically change the Text property of a control. Here's an example:

Private Sub Form_Dirty(Cancel As Integer)
'Flip the Enabled properties of the appropriate
'command buttons
Call FlipEnabled(Me, ActiveControl)
'Hide the form navigation buttons
Me.NavigationButtons = False
End Sub

This code, located in the frmClients form of the time and billing application, calls FlipEnabled to flip the command buttons on the form. This has the effect of enabling the Save and Cancel command buttons and disabling the other command buttons on the form. The code also removes the navigation buttons, prohibiting the user from moving to other records while the data is in a "dirty" state.

Undo


The Undo event executes before changes to a row are undone. The Undo event initiates when the user clicks the Undo button on the toolbar, taps the Esc key, or executes code that attempts to undo changes to the row. If you cancel the Undo event, the changes to the row are not undone. Here's an example:

Private Sub Form_Undo(Cancel As Integer)
'Ask user if they meant to undo changes
If MsgBox("You Have Attempted to Undo Changes " & _
"to the Current Row. Would You Like to Proceed " & _
"with the Undo Process?", _
vbYesNo) = vbYes Then
'If they respond yes, proceed with the undo
Cancel = False
Else
'If they respond no, cancel the undo
Cancel = True
End If
End Sub

This code, located in the frmProjects form of the time and billing application, displays a message to the user, asking him if he really wants to undo his changes. If he responds Yes, the Undo process proceeds. If he responds No, the Undo process is canceled.

Delete


The Delete event occurs when a user tries to delete a record, but before the record is removed from the table. This is a great way to place code that allows deleting a record only under certain circumstances. If the Delete event is canceled, the BeforeDelConfirm and AfterDelConfirm events (covered next) never execute, and the record is never deleted.

TIP

When the user deletes multiple records, the Delete event happens after each record is deleted. This allows you to evaluate a condition for each record and decide whether to delete each record.

BeforeDelConfirm


The BeforeDelConfirm event takes place after the Delete event, but before the Delete Confirm dialog box is displayed. If you cancel the BeforeDelConfirm event, the record being deleted is restored from the delete buffer, and the Delete Confirm dialog box is never displayed.

AfterDelConfirm


The AfterDelConfirm event occurs after the record is deleted, or when the deletion is canceled. If the code does not cancel the BeforeDelConfirm event, the AfterDelConfirm event takes place after Access displays the Confirmation dialog box.

Open


The Open event occurs when a form is opened but before the first record is displayed. With this event, you can control exactly what happens when the form first opens. The Open event of the time and billing application's frmProjects form looks like this:

Private Sub Form_Open(Cancel As Integer)
'If the Clients form is not loaded,
'display a message to the user and
'do not load the form
If Not IsLoaded("frmClients") Then
MsgBox "Open the Projects form using the Projects " & _
"button on the Clients form."
Cancel = True
End If
End Sub

This code checks to make sure the frmClients form is loaded. If it isn't, it displays a message box, and sets the Cancel parameter to True, which prohibits the form from loading.

Load


The Load event happens when a form opens, and the first record is displayed; it occurs after the Open event. A form's Open event can cancel the opening of a form, but the Load event can't. The following routine is placed in the Load event of the time and billing application's frmExpenseCodes form:

Private Sub Form_Load()
'If the form is opened in Data Entry mode
'and the OpenArgs property is not null,
'set the txtExpenseCode text box equal to
'the value of the opening arguments
If Me.DataEntry _
And Not (IsNull(Me.OpenArgs)) Then
Me.txtExpenseCode = Me.OpenArgs
End If
End Sub

This routine looks at the string that's passed as an opening argument to the form. If the OpenArgs string is not Null, and the form is opened in Data Entry mode, the txtExpenseCode text box is set equal to the opening argument. In essence, this code allows the form to be used for two purposes. If the user opens the form from the database container, no special processing occurs. On the other hand, if the user opens the form from the fsubTimeCardsExpenses subform, the form is opened in Data Entry mode, and the expense code that the user specified is placed in the txtExpenseCode text box.

Resize


The Resize event takes place when a form is opened or whenever the form's size changes.

Unload


The Unload event happens when a form is closed, but before Access removes the form from the screen. It's triggered when the user chooses Close from the File menu, quits the application by choosing End Task from the task list, or quits Windows, or when your code closes the form. You can place code that makes sure it's okay to unload the form in the Unload event, and you can also use the Unload event to place any code you want executed whenever the form is unloaded. Here's an example:

Private Sub Form_Unload(Cancel As Integer)
'Determine if the form is dirty
If Me.cmdSave.Enabled Then
'If form is dirty, ask user if they want to save
Select Case MsgBox("Do You Want To Save?", _
vbYesNoCancel + vbCritical, _
"Please Respond")
'If user responds yes, save record and allow unload
Case vbYes
DoCmd.RunCommand Command:=acCmdSaveRecord
Cancel = False
'If user responds no, undo changes to record and
'allow unload
Case vbNo
On Error Resume Next
DoCmd.RunCommand Command:=acCmdUndo
Cancel = False
'If user clicks Cancel, cancel unloading of form
Case vbCancel
Cancel = True
End Select
End If
End Sub

This code is in the Unload event of the frmClients form from the time and billing application. It checks whether the Save button is enabled. If it is, the form is in a dirty state. The user is prompted as to whether she wants to save changes to the record. If she responds yes, the code saves the data, and the form is unloaded. If she responds no, the code cancels changes to the record, and the form is unloaded. Finally, if she opts to cancel, the value of the Cancel parameter is set to False, and the form is not unloaded.

Close


The Close event occurs

after the Unload event, when a form is closed and removed from the screen. Remember, you can cancel the Unload event but not the Close event.

The following code is located in the Close event of the frmClients form that's part of the time and billing database:

Private Sub Form_Close()
'If the frmProjects form is loaded,
'unload it
If IsLoaded("frmProjects") Then
DoCmd.Close acForm, "frmProjects"
End If
End Sub

When the frmClients form is closed, the code tests whether the frmProjects form is open. If it is, the code closes it.

Activate


The Activate event takes place when the form gets focus and becomes the active window. It's triggered when the form opens, when a user clicks on the form or one of its controls, and when the SetFocus method is applied by using VBA code. The following code, found in the Activate event of the time and billing application's frmClients form, re-queries the fsubClients subform whenever the frmClients main form activates:

Private Sub Form_Activate()
'Requery form when it becomes active
'This ensures that changes made in the Projects form
'are immediately reflected in the Clients form
Me.fsubClients.Requery
End Sub

Deactivate


The Deactivate event occurs when the form loses focus, which happens when a table, query, form, report, macro, module, or the Database window becomes active.

However, the Deactivate event isn't triggered when a dialog, pop-up form, or another application becomes active. The following is an example of the use of the Deactivate event:

Private Sub Form_Deactivate()
'Use AllowEdits property setting to determine which toolbar to hide.
'Show Form View toolbar.
If Me.AllowEdits = True Then
DoCmd.ShowToolbar "Enter Or Edit Products 2", acToolbarNo
Else
DoCmd.ShowToolbar "Enter Or Edit Products 1", acToolbarNo
End If
DoCmd.ShowToolbar "Form View", acToolbarWhereApprop
End Sub

This code evaluates the AllowEdits property to determine which custom toolbar is currently active. It hides the appropriate toolbar and shows the standard Form View toolbar.

GotFocus


The GotFocus event happens when a form gets focus, but only if there are no visible, enabled controls on the form. This event is rarely used for a form.

LostFocus


The LostFocus event occurs when a form loses focus, but only if there are no visible, enabled controls on the form. This event, too, is rarely used for a form.

Click


The Click event takes place when the user clicks on a blank area of the form, on a disabled control on the form, or on the form's record selector.

DblClick


The DblClick event happens when the user double-clicks on a blank area of the form, on a disabled control on the form, or on the form's record selector.

MouseDown


The MouseDown event occurs when the user clicks on a blank area of the form, on a disabled control on the form, or on the form's record selector. However, it happens

before the Click event fires. You can use it to determine which mouse button was pressed.

MouseMove


The MouseMove event takes place when the user moves the mouse over a blank area of the form, over a disabled control on the form, or over the form's record selector. It's generated continuously as the mouse pointer moves over the form. The MouseMove event occurs

before the Click event fires.

MouseUp


The MouseUp event occurs when the user releases the mouse button. Like the MouseDown event, it happens before the Click event fires. You can use the MouseUp event to determine which mouse button was pressed.

KeyDown


The KeyDown event happens if there are no controls on the form, or if the form's KeyPreview property is set to Yes. If the latter condition is true, all keyboard events are previewed by the form and occur for the control that has focus. If the user presses and holds down a key, the KeyDown event occurs repeatedly until the user releases the key. Here's an example:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
'If the form is dirty and the user presses page up or
'page down, ignore the keystroke
If Me.Dirty Then
If KeyCode = vbKeyPageDown Or _
KeyCode = vbKeyPageUp Then
KeyCode = 0
End If
End If
End Sub

This code, found in the frmClients form that is part of the time and billing application, tests to see if the form is in a dirty state. If it is, and the user presses the Page Down or Page Up key, Access ignores the keystroke. This prevents the user from moving to other records without first clicking the Save or Cancel command buttons.

KeyUp


Like the KeyDown event, the KeyUp event occurs if there are no controls on the form, or if the form's KeyPreview property is set to Yes. The KeyUp event takes place only once, though, regardless of how long the user presses the key. You can cancel the keystroke by setting KeyCode to Zero.

KeyPress


The KeyPress event occurs when the user presses and releases a key or key combination that corresponds to an ANSI code. It takes place if there are no controls on the form, or if the form's KeyPreview property is set to Yes. You can cancel the keystroke by setting KeyCode to Zero.

Error


The Error event triggers whenever an error happens while the user is in the form. Microsoft Jet Engine errors are trapped, but Visual Basic errors aren't. You can use this event to suppress the standard error messages. You must handle Visual Basic errors using standard On Error techniques. Both the Error event and handling Visual Basic errors are covered in Chapter 16, "Error Handling: Preparing for the Inevitable."

Filter


The Filter event takes place whenever the user selects the Filter By Form or Advanced Filter/Sort options. You can use this event to remove the previous filter, enter default settings for the filter, invoke your own custom filter window, or prevent certain controls from being available in the Filter By Form window. The later section "Taking Advantage of Built-In, Form-Filtering Features" covers filters in detail.

ApplyFilter


The ApplyFilter event occurs when the user selects the Apply Filter/Sort, Filter By Selection, or Remove Filter/Sort options. It also takes place when the user closes the Advanced Filter/Sort window or the Filter By Form window. You can use this event to make sure that the applied filter is correct, to change the form's display before the filter is applied, or to undo any changes you made when the Filter event occurred. The later section "Taking Advantage of Built-In, Form-Filtering Features" covers filters in detail.

Timer


The Timer event and a form's TimerInterval property work hand in hand. You can set the TimerInterval property to any value between 0 and 2,147,483,647. The value used determines the frequency, expressed in milliseconds, at which the Timer event will occur. For example, if the TimerInterval property is set to 0, the Timer event will not occur at all; if set to 5000 (5000 milliseconds), the Timer event will occur every five seconds. The following example uses the Timer event to alternate the visibility of a label on the form. This produces a flashing effect. The TimerInterval property can be initially set to any valid value other than 0, but will be reduced by 50 milliseconds each time the code executes. This has the effect of making the control flash faster and faster. The Timer events continue to occur until the TimerInterval property is finally reduced to 0.

Private Sub Form_Timer()
'If Label1 is visible, hide it, otherwise show it
If Me.Label2.Visible = True Then
Me.Label2.Visible = False
Else
Me.Label2.Visible = True
End If
'Decrement the timer interval, causing the
'label to flash more quickly
Me.TimerInterval = Me.TimerInterval - 50
'Once the timer interval becomes zero,
'make the label visible
If Me.TimerInterval = 0 Then
Me.Label2.Visible = True
End If
End Sub

Understanding the Sequence of Form Events


One of the mysteries of events is the order in which they occur. One of the best ways to figure this out is to place Debug.Print statements in the events you want to learn about. This technique is covered in Chapter 15, "Debugging: Your Key to Successful Development." Keep in mind that event order isn't an exact science; it's nearly impossible to guess when events will happen in all situations. It's helpful, though, to understand the basic order in which certain events do take place.

What Happens When a Form Is Opened?

When a user opens a form, the following events occur:

Open->Load->Resize->Activate->Current

After these Form events take place, the Enter and GotFocus events of the first control occur. Remember that the Open event provides the only opportunity to cancel opening the form.

What Happens When a Form Is Closed?

When a user closes a form, the following events take place:

Unload->Deactivate->Close

Before these events occur, the Exit and LostFocus events of the active control trigger.

What Happens When a Form Is Sized?

When a user resizes a form, what happens depends on whether the form is minimized, restored, or maximized. When the form minimizes, here's what happens:

Resize->Deactivate

When a user restores a minimized form, these events take place:

Activate->Resize

When a user maximizes a form or restores a maximized form, just the Resize event occurs.

What Happens When Focus Shifts from One Form to Another?

When a user moves from one form to another, the Deactivate event occurs for the first form; then the Activate event occurs for the second form. Remember that the Deactivate event doesn't take place if focus moves to a dialog box, a pop-up form, or another application.

What Happens When Keys Are Pressed?

When a user types a character, and the form's KeyPreview property is set to True, the following events occur:

KeyDown->KeyPress->Dirty->KeyUp

If you trap the KeyDown event and set the KeyCode to Zero, the remaining events never happen. The KeyPress event captures only ANSI keystrokes. This event is the easiest to deal with. However, you must handle the KeyDown and KeyUp events when you need to trap for non-ANSI characters, such as Shift, Alt, and Ctrl.

What Happens When Mouse Actions Take Place?

When a user clicks the mouse button, the following events occur:

MouseDown->MouseUp->Click

/ 544