Copyright: Microsoft Access for Windows 95


Microsoft Access Language Elements That Apply to Custom Controls

In addition to the language elements specific to a custom control, some existing Microsoft Access language elements also apply to custom controls. For information on how these language elements work, see the Microsoft Access topic on each element.

Properties

The following Microsoft Access properties apply to custom controls:

BorderColor	Left	OnUpdated
BorderStyle	Locked	SpecialEffect
BorderWidth	Name	TabIndex
Class	Object	TabStop
ControlSource (only available for custom controls that support binding)	OLEClass	Tag
ControlTipText	OnEnter	Top
DisplayWhen	OnExit	Verb
Enabled	OnGotFocus	Visible
Height	OnLostFocus	Width
HelpContextId
Events

The following Microsoft Access events apply to custom controls:

Enter	GotFocus	Updated
Exit	LostFocus


Using a Custom Control's Custom Property Sheet

When setting the properties of a custom control, you may need or prefer to use the control's custom property sheet. This custom property sheet provides an alternative to the list of properties in the Microsoft Access property sheet for setting custom control properties in Design view.

Two Ways to Set Properties

The reason for the custom property sheet is that not all applications that use custom controls provide a property sheet like the one in Microsoft Access. The custom property sheet provides an interface for setting key control properties regardless of the interface supplied by the hosting application.

For some custom control properties, you can choose either of these two locations to set the property:

The Microsoft Access property sheet

The custom control custom property sheet

In some cases, the custom property sheet is the only way to set a property in Design view. This is usually the situation when the interface needed to set a property doesn't work inside the Microsoft Access property sheet. For example, the GridFont property for the Calendar Control has a number of arguments; you can't set more than one argument per property in the Microsoft Access property sheet.

Finding the Custom Property Sheet

Not all custom controls provide a custom property sheet. To see whether a control provides this custom property sheet, look for the Custom property in the Microsoft Access property sheet for this control. If the list of properties contains the name Custom, then the control provides the custom property sheet.

Using the Custom Property Sheet

After you click the Custom property box in the Microsoft Access property sheet, click the Build button to the right of the property box to display the control's custom property sheet, often presented as a tabbed dialog box. Choose the tab that contains the interface for setting the properties that you want to set.

After you make changes in one tab, you can often apply those changes immediately by clicking the Apply button (if provided). You can click other tabs to set other properties as needed. To approve all changes made in the custom property sheet, click the OK button. To return to the Microsoft Access property sheet without changing any property settings, click the Cancel button.

You can also view the custom property sheet by clicking the Properties subcommand of the custom control Object command (for example, Calendar Control Object) on the Edit menu, or by clicking this same subcommand on the shortcut menu for the custom control. In addition, some properties in the Microsoft Access property sheet for the custom control, like the GridFontColor property of the Calendar Control, have a Build button to the right of the property box. When you click the Build button, the custom property sheet is displayed, with the appropriate tab selected (for example, Colors).


Viewing a Custom Control's About Box

To view an About box showing version and copyright information for a custom control, click the About property box in the Microsoft Access property sheet. Then click the Build button to the right of the property box.


 Using the Properties, Methods, and Events of a Custom Control

This topic contains useful information on setting and using custom control language elements, and points out some new features of custom controls in Microsoft Access 95.

General

When using custom controls with Microsoft Access 95, you no longer need to use the Object property when referring to properties and methods in syntax expressions. For example, the following two syntax lines are now normally equivalent:

OLEControl0.Object.MonthLength = "Short"

OLEControl0.MonthLength = "Short"

The only exception is if the name of the custom control language element is the same as that of an existing Microsoft Access language element that also applies to this custom control. In this case, you must still use the .Object syntax.

Properties

Custom control properties now appear in the Microsoft Access property sheet. You can set most of these properties in either the custom control custom property sheet or the Microsoft Access property sheet.

Note	The custom control properties are not listed in the Properties collection. The only way to access these properties is using the syntax shown in the previous section.

Events

For Microsoft Access events like Enter that apply to custom controls, you can run a macro or event procedure when the event occurs by setting the event property to the name of the macro or [Event Procedure]. However, for events that are specific to custom controls like the NewMonth event of the Calendar Control, you must go into the form module window, select the name of the custom control from the Object box, and then select the event from the Proc box. This creates an event procedure for the custom control event that runs when the event occurs. You can also duplicate the syntax that is created in this case for the event procedure if you want to create it yourself.

If a Microsoft Access event and a custom control event with the same name both apply to a custom control object, Microsoft Access appends "Object" to the custom control event in the Proc box drop-down list. This enables you to run a different procedure when each event occurs.


Application

Application Object

Application Property


ApplyFilter

ApplyFilter Event

ApplyFilter Method


Beep

Beep Action

Beep Method


BeforeInsert, AfterInsert

BeforeInsert, AfterInsert Events

BeforeInsert, AfterInsert Properties


BeforeUpdate, AfterUpdate

BeforeUpdate, AfterUpdate Events

BeforeUpdate, AfterUpdate Properties


CancelEvent

CancelEvent Action

CancelEvent Method


Close

Close Action

Close Method


CopyObject

CopyObject Action

CopyObject Method


DeleteObject

DeleteObject Action

DeleteObject Method


DoMenuItem

DoMenuItem Action

DoMenuItem Method


Echo

Echo Method

Echo Method (DoCmd Object)


Filter

Filter Event

Filter Property (Microsoft Access)


FindNext

FindNext Action

FindNext Method


FindRecord

FindRecord Action

FindRecord Method


Form

Form Object

Form Property


Format

Format Event

Format Property


GoToControl

GoToControl Action

GoToControl Method


GoToPage

GoToPage Method

GoToPage Method (DoCmd Object)


GoToRecord

GoToRecord Action

GoToRecord Method


Hourglass

Hourglass Action

Hourglass Method


KeepTogether

KeepTogether Property - Groups

KeepTogether Property - Sections


Maximize

Maximize Action

Maximize Method


Minimize

Minimize Action

Minimize Method


MoveSize

MoveSize Action

MoveSize Method


OpenForm

OpenForm Action

OpenForm Method


OpenModule

OpenModule Action

OpenModule Method


GoToPage
OpenQuery

OpenQuery Action

OpenQuery Method


OpenReport

OpenReport Action

OpenReport Method


OutputTo

OutputTo Action

OutputTo Method


PrintOut

PrintOut Action

PrintOut Method


Quit

Quit Method

Quit Method (DoCmd Object)


Rename

Rename Action

Rename Method


RepaintObject

RepaintObject Action

RepaintObject Method


Report

Report Object

Report Property


Requery

Requery Method

Requery Method (DoCmd Object)


Restore

Restore Action

Restore Method


RunMacro

RunMacro Action

RunMacro Method


RunSQL

RunSQL Action

RunSQL Method


Save

Save Action

Save Method


SelectObject

SelectObject Action

SelectObject Method


SendObject

SendObject Action

SendObject Method


SetMenuItem

SetMenuItem Action

SetMenuItem Method (DoCmd Object)


SetWarnings

SetWarnings Action

SetWarnings Method


ShowAllRecords

ShowAllRecords Action

ShowAllRecords Method


ShowToolbar

ShowToolbar Action

ShowToolbar Method


TransferDatabase

TransferDatabase Action

TransferDatabase Method


TransferSpreadsheet

TransferSpreadsheet Action

TransferSpreadsheet Method


TransferText

TransferText Action

TransferText Method


Visible

Visible Property (Application Object)

Visible Property (Microsoft Access)


Controls Collection

The Controls collection contains all of the controls on a form or report. The Controls collection is a member of a Form or Report object.

Remarks

You can enumerate individual controls, count them, and set their properties in the Controls collection. For example, you can enumerate the Controls collection of a particular form and set the Height property of each control to a specified value.

Tip   The For Each...Next statement is useful for enumerating a collection.

It is faster to refer to the Controls collection implicitly, as in the following examples, which refer to a control called NewData on a form named OrderForm. Of the following syntax examples, Me!NewData is the fastest way to refer to the control.

Me!NewData	' Or Forms!OrderForm!NewData.

Me![New Data]	' Use if control name contains space.

Me("NewData")	' Performance slightly slower.

You can also refer to an individual control by referring explicitly to the Controls collection.

Me.Controls!NewData	' Or Forms!OrderForm.Controls!NewData.

Me.Controls![New Data]

Me.Controls("NewData")

Additionally, you can refer to a control by its index in the collection. The Controls collection is indexed beginning with zero.

Me(0)	' Refer to first item in collection.

Me.Controls(0)

Note   You can use the Me keyword to represent a form or report within code only if you're referring to the form or report from code within the form module or report module. If you're referring to a form or report from a standard module or a different form or report's module, you must use the full reference to the form or report.


AddMenu Action

The AddMenu action can be used to:

Create a custom menu bar for a form or report. The custom menu bar replaces the built-in menu bar for the form or report.

Create a custom shortcut menu for a form, form control, or report. The custom shortcut menu replaces the built-in shortcut menu for the form, form control, or report.

Create a global menu bar. The global menu bar replaces the built-in menu bar for all Microsoft Access windows, except where you have added a custom menu bar for a form or report.

Create a global shortcut menu. The global shortcut menu replaces the built-in shortcut menu for all Microsoft Access windows, except where you have added a custom shortcut menu for a form, form control, or report.

Setting

The AddMenu action uses the following arguments.

Action argument	Description

Menu Name	The name of the drop-down menu to add to the custom menu bar or global menu bar. This is a required argument for custom menu bars and global menu bars. This argument is ignored for custom shortcut menus and global shortcut menus.

Menu Macro Name	The name of the macro group that contains the macros for the menu's commands. This is a required argument.

If you run a macro containing the AddMenu action in a library database, Microsoft Access looks for the macro group with this name in the current database only.

Status Bar Text	The text to display in the status bar when the menu is selected. This argument is ignored for custom shortcut menus and global shortcut menus.

Remarks

To create a custom menu bar, a custom shortcut menu, a global menu bar, or a global shortcut menu, you must do the following:

1	Create a menu bar macro that contains an AddMenu action for each drop-down menu you want on the custom menu bar or global menu bar. For custom shortcut menus and global shortcut menus, the menu bar macro should contain just one AddMenu action.

2	Assign commands to each drop-down menu by creating a macro group for each menu. Each command runs the set of actions defined by a macro in this macro group. For custom shortcut menus and global shortcut menus, create just one macro group, in which each macro contains the set of actions for one of the commands in the shortcut menu.

3	Attach the menu bar macro to the appropriate Microsoft Access object:

For custom menu bars, enter the name of the menu bar macro in the MenuBar property for the form or report.

For custom shortcut menus, enter the name of the menu bar macro in the ShortcutMenuBar property for the form, form control, or report.

For global menu bars, click Startup on the Tools menu, then in the Startup dialog box enter the name of the menu bar macro in the Shortcut Menu Bar box.

For global shortcut menus, click Startup on the Tools menu, then in the Startup dialog box enter the name of the menu bar macro in the Shortcut Menu Bar box.

Tip   You can use the Menu Builder to create any of the custom or global menu bars and shortcut menus by clicking the Build button next to the property box or Startup dialog option box where you specify the menu bar macro. The Menu Builder creates and names the menu bar macro and the macro groups containing the actions for the menu commands and subcommands on the menu you create. If you use the Menu Builder to create the menu bar macro and the macro groups for the menus, you can also use the Menu Builder to edit these macros and macro groups.

However, if you create the custom menu bar or custom shortcut menu in the Macro window, you can't use the Menu Builder to edit the menu bar macro and macro groups because the Menu Builder places restrictions on the names it uses for the menu bar macro and macro groups, and on the kinds of actions it uses in the macros.

For global shortcut menus and custom shortcut menus, add only one menu in the Menu Builder. Any additional menus are ignored.

Each menu on the menu bar requires a separate AddMenu action.

The custom and global menu bars and shortcut menus replace the built-in menu bars and shortcut menus for the objects they're attached to. If you want to retain certain Microsoft Access commands to use on these menus, use the DoMenuItem action to put the commands into the macro groups for the desired menus.

You can run a macro from a menu command by using the RunMacro action in the macro for the command.

Note   AddMenu actions can be used only in a menu bar macro specified by the MenuBar or ShortcutMenuBar property of a form, form control, or report, or by the Menu Bar box or Shortcut Menu Bar box in the Startup dialog box, available by clicking Startup on the Tools menu. Menu bar macros should contain only AddMenu actions.

You can create a submenu for a custom menu or a custom shortcut menu by using the AddMenu action in a macro group specified by the Menu Macro Name argument. If you put an AddMenu action in such a macro group, Microsoft Access creates a submenu with the menu name and status bar text specified by the Menu Name and Status Bar Text arguments for this AddMenu action. The submenu contains the commands defined by the macros in the macro group specified by the Menu Macro Name argument for the AddMenu action. The Menu Name and Status Bar Text columns of such an AddMenu action are ignored, since this action defines a submenu, not a command on the top-level menu. You can create multiple levels of submenus by using AddMenu actions in the macro groups for each level of menu.

Macro conditions are supported in the top-level menu bar macro only. In other words, you can use a condition in a menu bar macro to determine if a particular menu will be displayed on the custom menu bar or global menu bar, but only for the menus on the top level of the menu bar. You can't use conditions to display or hide commands or submenus on the menus. You can also use a condition to hide or show a custom shortcut menu or global shortcut menu.

Note   In Microsoft Access version 2.0, if you used the AddMenu action to put the Add-Ins submenu on the File menu of a custom menu bar, Microsoft Access automatically added the appropriate Add-Ins submenu items to your custom menu. In Microsoft Access for Windows 95, the Add-Ins submenu has moved to the Tools menu. Microsoft Access adds the submenu items to this menu as before. However, it will not add the submenu items to an Add-Ins submenu on the File menu of a custom menu bar or global menu bar. If you had an Add-Ins submenu on one or more of your custom menu bars in version 2.0, you may want to rewrite your macros and move the Add-Ins submenu to the Tools menu.

The AddMenu action isn't available in Visual Basic. You can, however, set the MenuBar or ShortcutMenuBar property in Visual Basic to attach a custom menu bar or custom shortcut menu to a form, form control, or report. You can set the StartupMenuBar property (the programmatic equivalent of setting the Menu Bar box) to create a global menu bar. You can also set the MenuBar property of the Application object to create a global menu bar. Similarly, you can set the StartupShortcutMenuBar property (the programmatic equivalent of setting the Shortcut Menu Bar box) or the ShortcutMenuBar property of the Application object to create a global shortcut menu.


ApplyFilter Action

You can use the ApplyFilter action to apply a filter, a query, or an SQL WHERE clause to a table, form, or report to restrict or sort the records in the table, or the records from the underlying table or query of the form or report. For reports, you can use this action only in a macro specified by the report's OnOpen event property.

Setting

The ApplyFilter action uses the following arguments.

Action argument	Description

Filter Name	The name of a filter or query that restricts or sorts the records of the table, form, or report. You can enter the name of either an existing query or a filter that has been saved as a query.

Where Condition	A valid SQL WHERE clause (without the word WHERE) or an expression that restricts the records of the table, form or report.

Note   In the Where Condition expression, the left side of the expression typically contains a field name from the underlying table or query for the form or report. The right side of the expression typically contains the criteria you want to apply to this field in order to restrict or sort the records. For example, the criteria can be the name of a control on another form that contains the value you want the records in the first form to match. The name of the control should be fully qualified: Forms!formname!controlname.

The maximum length of the Where Condition argument is 256 characters. If you need to enter a longer SQL WHERE clause, use the ApplyFilter method of the DoCmd object in Visual Basic. You can enter SQL WHERE clause statements of up to 32,768 characters in Visual Basic.

Note   You must use one or both arguments. You can use the Filter Name argument if you've already defined a filter that provides the appropriate data. You can use the Where Condition argument to enter the restriction criteria directly. If you use both arguments, Microsoft Access applies the WHERE clause to the results of the filter.

Remarks

You can apply a filter or query to a form in Form view or Datasheet view.

For tables and forms, this action is similar to clicking Apply Filter/Sort on the Records menu or clicking the Apply Filter button on the toolbar. The menu command or button applies the most recently created filter to the table or form, whereas the ApplyFilter action applies a specified filter or query.

If you point to Filters on the Records menu and then click Advanced Filter/Sort after running the ApplyFilter action, the Advanced Filter/Sort window shows the filter criteria you have selected with this action.

To remove a filter and display all of the records for a table or form, you can use the ShowAllRecords action, the Remove Filter/Sort command on the Records menu, or the Remove Filter button on the toolbar.

When you save a table or form, Microsoft Access saves any filter currently defined in that object, but won't apply the filter automatically the next time the object is opened (although it will automatically apply any sort you applied to the object before it was saved). If you want to apply a filter automatically when a form is first opened, specify a macro using the ApplyFilter action or an event procedure using the ApplyFilter method of the DoCmd object as the OnOpen event property setting of the form. You can also apply a filter using the OpenForm or OpenReport action, or their corresponding methods. To apply a filter automatically when a table is first opened, you can open the table using a macro containing the OpenTable action, followed immediately by an ApplyFilter action.


Beep Action

You can use the Beep action to sound a beep tone through the computer's speaker.

Setting

The Beep action doesn't use any arguments.

Remarks

You can use the Beep action to signal the following occurrences:

Important screen changes have occurred.

The wrong kind of data has been entered in a control. For example, the user has entered numeric data in a Text control.

A macro has reached a specified point or has completed its actions.

The frequency and duration of the beep depend on hardware, which may vary between computers.

To run the Beep action in Visual Basic, use the Beep method of the DoCmd object.


CancelEvent Action

You can use the CancelEvent action to cancel the event that caused Microsoft Access to run the macro containing this action. The macro name is the setting of an event property such as BeforeUpdate, OnOpen, OnUnload, or OnPrint.

Setting

The CancelEvent action doesn't use any arguments.

Remarks

In a form, you typically use the CancelEvent action in a validation macro with the BeforeUpdate event property. When a user enters data in a control or record, Microsoft Access runs the macro before adding the data to the database. If the data fails the validation conditions in the macro, the CancelEvent action cancels the update process before it starts.

Often, you can use this action with the MsgBox action to indicate that the data has failed the validation conditions and to provide helpful information about the kind of data that should be entered.

The following events can be canceled by the CancelEvent action:

ApplyFilter	Delete	MouseDown
BeforeDelConfirm	Exit	NoData
BeforeInsert	Filter	Open
BeforeUpdate	Format	Print
DblClick	KeyPress	Unload
Note   You can use the CancelEvent action with the MouseDown event only to cancel the event that occurs when you click the right mouse button.

If a control's OnDblClick event property setting specifies a macro containing the CancelEvent action, the action cancels the double-click event.

For events that can be canceled, the default behavior for the event (that is, what Microsoft Access typically does when the event occurs) occurs after the macro for the event runs. This enables you to cancel the default behavior. For example, when you double-click a word that the insertion point is on in a text box, Microsoft Access normally selects the word. You can cancel this default behavior in the macro for the DblClick event and perform some other action, such as opening a form containing information about the data in the text box. For events that can't be canceled, the default behavior occurs before the macro runs.

Note   If a form's OnUnload event property specifies a macro that carries out a CancelEvent action, you won't be able to close the form. You must either correct the condition that caused the CancelEvent action or open the macro and delete the CancelEvent action to close the form. If the form is a modal form, you won't be able to open the macro.

To carry out the CancelEvent action in Visual Basic, use the CancelEvent method of the DoCmd object.


Close Action

You can use the Close action to close either a specified Microsoft Access window or the active window if none is specified.

Setting

The Close action uses the following arguments.

Action argument	Description

Object Type	The type of object whose window you want to close. Click Table, Query, Form, Report, Macro, or Module in the drop-down list in the Action Arguments section of the Macro window. To select the active window, leave this argument blank.

Object Name	The name of the object to be closed. The Object Name box shows all objects in the database of the type selected with the Object Type argument. Click the object to close. If you left the Object Type box blank, leave this box blank also.

Save	Whether to save changes to the object when it's closed. You can click Yes to save the object, No to close the object without saving it, and Prompt to prompt the user whether or not to save the object. The default is Prompt.

Remarks

The Close action works on all database objects that the user can explicitly open or close. This action has the same effect as selecting an object and then closing it by clicking Close on the File menu, clicking Close on the Control menu for the object's window, or clicking the Close button for the object.

If the Save argument is set to Prompt and the object hasn't already been saved before the Close action is carried out, a dialog box prompts the user to save the object before the macro closes it. If you've set the Warnings On argument of the SetWarnings action to No, the dialog box isn't displayed and the object is automatically saved.

To run the Close action in Visual Basic, use the Close method of the DoCmd object.


CopyObject Action

You can use the CopyObject action to copy the specified database object to a different Microsoft Access database or to the same database under a new name. For example, you can copy or save an existing object in another database or quickly create a similar object with changes.

Setting

The CopyObject action uses the following arguments.

Action argument	Description

Destination Database	A valid path and filename for the destination database. Leave this argument blank if you want to select the current database.

If you run a macro containing the CopyObject action in a library database and leave this argument blank, Microsoft Access will copy the object into the library database.

New Name	A new name for the object. When copying to a different database, leave this argument blank to keep the same name.

Source Object Type	The object type you want to copy. Click Table, Query, Form, Report, Macro, or Module in the Source Object Type box in the Action Arguments section of the Macro window. To copy the object selected in the Database window, leave this box blank.

Source Object Name	The name of the object to be copied. The Source Object Name box shows all objects in the database of the type selected by the Source Object Type argument. In the Source Object Type box, click the object to copy. If you left the Source Object Type blank, leave this box blank also.

If you run a macro containing the CopyObject action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

You must enter a value for either one or both of the Destination Database and New Name arguments for this action.

If you leave the Source Object Type and Source Object Name arguments blank, Microsoft Access copies the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action with the In Database Window argument set to Yes.

The CopyObject action is similar to selecting an object in the Database window, clicking Copy on the Edit menu, and then clicking Paste on the Edit menu. The Paste As dialog box appears so you can give the object a new name. The CopyObject action performs all of these steps automatically.

You can also copy an object selected in the Database window, or an open object in the Table window, Query window, Form window, Report window, Macro window, or Module window by clicking Save As/Export on the File menu. The Save As dialog box gives you the option of saving a copy of the object in the current database with a new name, or saving the object in another database. If this object has already been saved and you save it in the current database with a new name, the original version still exists with its old name.

The path and filename of the destination database must exist before the macro runs the CopyObject action. If they don't exist, Microsoft Access displays an error message.

To run the CopyObject action in Visual Basic, use the CopyObject method of the DoCmd object.


DoMenuItem Action

You can use the DoMenuItem action to carry out a Microsoft Access menu command.

You can use this action to do the following:

Carry out any Microsoft Access command from a macro. You must select a command that is appropriate for your current view when the macro carries out the command. For example, a macro can't carry out any of the Records menu commands if the active object is in table Design view, form Design view, query Design view, or report Design view.

Add a Microsoft Access command to a custom menu bar for a form or report, or to a menu on the global menu bar. For each command you want to add, enter a DoMenuItem action in the macro group for that menu.

Add a Microsoft Access command to a custom shortcut menu for a form, form control, or report, or to the global shortcut menu. For each command you want to add, enter a DoMenuItem action in the macro group for the custom shortcut menu or global shortcut menu.

Setting

The DoMenuItem action uses the following arguments.

Action argument	Description

Menu Bar	The name of the menu bar that contains the command you want to carry out. The Menu Bar box list in the Action Arguments section of the Macro window shows the different views in which menu bars appear. This is a required argument.

Menu Name	The name of the menu that contains the command you want to carry out. The Menu Name box shows all menus on the menu bar that you selected with the Menu Bar argument. This is a required argument.

Command	The command you want to carry out. The Command box shows all commands in the menu that you selected with the Menu Name argument. This is a required argument.

Subcommand	The subcommand you want to carry out. This applies only if the desired command has a submenu.

Remarks

The DoMenuItem action has the same effect as clicking the specified command on a Microsoft Access menu. If clicking a command displays a dialog box, the dialog box is also displayed when you carry out the DoMenuItem action. You can use the SendKeys action to enter the appropriate information in the dialog box.

If you open a Microsoft Access version 1.x or version 2.0 database in Microsoft Access for Windows 95, the arguments for the DoMenuItem action in macros in this database show the appropriate menus and menu commands. However, you can't edit objects from a version 1.x or version 2.0 database using a Microsoft Access 95 database. When you convert the database to Microsoft Access 95, the DoMenuItem action arguments will show the new menus and menu commands.

Note   The Microsoft Access 95 File menu shows the most recently used databases. You can click one of these databases instead of clicking Open Database. These database items do not appear in the drop-down list for the Command Name argument for the File Menu, and are not available using the DoMenuItem action in a macro.

To run the DoMenuItem action in Visual Basic, use the DoMenuItem method of the DoCmd object.


Echo Action

You can use the Echo action to specify whether echo is turned on. For example, you can use this action to hide or show the results of a macro while it runs.

Setting

The Echo action uses the following arguments.

Action argument	Description

Echo On	Click Yes to turn echo on or No to turn it off. The default is Yes.

Status Bar Text	The text to display in the status bar when echo is turned off. For example, when echo is turned off, the status bar can display "The macro is running."

Remarks

When Microsoft Access runs a macro, screen updating often shows information not essential to the functioning of the macro. When you set the Echo On argument to No, the macro runs without updating the screen. When the macro finishes, Microsoft Access automatically turns echo back on and repaints the window. The No setting for Echo On doesn't affect the macro or its results.

The Echo action doesn't suppress the display of modal dialog boxes, such as error messages, or pop-up forms, such as property sheets. You can use these to gather or display information when echo is turned off. Use the SetWarnings action to turn off all message or dialog boxes except error message boxes and dialog boxes that require the user to enter information.

You can run the Echo action more than once in a macro. This allows you to change the status bar text while the macro runs.

If you turn echo off, you can use the Hourglass action to change the mouse pointer into an hourglass (or whatever mouse pointer icon you have set for "Busy" in Microsoft Windows 95 or "Wait" in Windows NT) to provide a visual indication that the macro is running.

To run the Echo action in Visual Basic, use the Echo method of the DoCmd object.


FindNext Action

You can use the FindNext action to find the next record that meets the criteria specified by the previous FindRecord action or the Find In Field dialog box, available by clicking Find on the Edit menu. You can use the FindNext action to search repeatedly for records. For example, you can move successively through all the records for a specific customer.

Setting

The FindNext action doesn't use any arguments. The FindNext action finds the next record that meets the criteria set either by the FindRecord action or in the Find In Field dialog box. The arguments for the FindRecord action are shared with the options in the Find In Field dialog box.

To set the search criteria, use the FindRecord action. Typically, you enter a FindRecord action in a macro and then use the FindNext action to find succeeding records that meet the same criteria. To search for records only when a certain condition is met, you can enter a conditional expression in the Condition box of the FindNext action.

Remarks

This action has the same effect as using the Find Next button in the Find In Field dialog box.

Note   While the FindRecord action corresponds to Find on the Edit menu for tables, queries, and forms, it does not correspond to Find on the Edit menu in the Module window. You can't use the FindRecord action or FindNext action to search for text in modules.

Tip   If you've set the Only Current Field argument of the FindRecord action to Yes, you may need to use the GoToControl action to move the focus to the control containing the data you're searching for before you use the FindNext action.

To run the FindNext action in Visual Basic, use the FindNext method of the DoCmd object.


FindRecord Action

You can use the FindRecord action to find the first record following the current record that meets the criteria specified by the FindRecord action arguments. You can find records in the active table datasheet, query datasheet, form datasheet, or form.

Setting

The FindRecord action uses the following arguments.

Action argument	Description

Find What 	Specifies the data you want to find in the record. Enter the text, number, or date you want to find or type an expression, which is preceded by an equal sign (=). You can use wildcard characters. This is a required argument.

Match	Specifies where the data is located in the field. You can specify a search for data in any part of the field (Any Part Of Field), for data that fills the entire field (Whole Field), or for data located at the beginning of the field (Start Of Field). The default is Whole Field.

Match Case 	Specifies whether the search is case-sensitive (uppercase and lowercase letters must match exactly). Click Yes to conduct a case-sensitive search or No to search without matching uppercase and lowercase letters exactly. The default is No.

Search	Specifies whether the search proceeds from the current record up to the beginning of the records (Up); down to the end of the records (Down); or down to the end of the records and then from the beginning of the records to the current record, so all records are searched (All). The default is All.

Search As Formatted	Specifies whether the search includes formatted data. If you click Yes, Microsoft Access searches for the data as it is formatted and displayed in the field. If you click No, Microsoft Access searches for the data as it is stored in the database, which is not always the same as it is displayed. The default is No.

You can use this feature to restrict the search to data in a particular format. For example, click Yes and enter 1,234 in the Find What argument to find a value of 1,234 in a field formatted to include commas. Click No if you want to enter 1234 to search for the data in this field.

To search for dates, click Yes to find a date exactly as it is formatted, such as 03-March-1991. If you click No, enter the date in the Find What argument in the format set in the Regional Settings Properties dialog box in the Microsoft Windows Control Panel. (This is the Short Date style found on the Date tab of the Regional Settings Properties dialog box.) For example, if the Short Date style format is set to M/d/yy, you can enter 3/9/91, and Microsoft Access will find all entries in a Date field that correspond to March 9, 1991, regardless of how this field is formatted.

Note   This argument takes effect only if the current field is a bound control, the Match argument is set to Whole Field, the Only Current Field argument is set to Yes, and the Match Case argument is set to No.

If you set Match Case to Yes or Only Current Field to No, you must also set Search As Formatted to Yes.

Only Current Field	Specifies whether the search is confined to the current field in each record or includes all fields in each record. The current field search is faster. Click Yes to confine the search to the current field or No to search in all fields in each record. The default is Yes.

Find First	Specifies whether the search starts at the first record or at the current record. Click Yes to start at the first record. Click No to start at the current record. The default is Yes.

Remarks

When a macro runs the FindRecord action, Microsoft Access moves to the next record containing the specified data and selects the data in the record.

The FindRecord action is equivalent to clicking Find on the Edit menu, and its arguments are the same as the options in the Find In Field dialog box. If you set the FindRecord action arguments in the Macro window and then run the macro, you'll see the corresponding options selected in the Find In Field dialog box when you click Find.

Microsoft Access retains the most recent FindRecord arguments during a database session so that you don't need to enter the same criteria repeatedly as you perform subsequent FindRecord operations. If you leave an argument blank, Microsoft Access uses the most recent setting for the argument, as set either by a previous FindRecord action or in the Find In Field dialog box.

When you want to find a record using a macro, use the FindRecord action, not the DoMenuItem action with arguments set to run the Find command.

Note   While the FindRecord action corresponds to Find on the Edit menu for tables, queries, and forms, it does not correspond to Find on the Edit menu in the Module window. You can't use the FindRecord action to search for text in modules.

To run the FindRecord action in Visual Basic, use the FindRecord method of the DoCmd object.


GoToControl Action

You can use the GoToControl action to move the focus to the specified field or control in the current record of the open form, form datasheet, table datasheet, or query datasheet. You can use this action when you want a particular field or control to have the focus. This field or control can then be used for comparisons or FindRecord actions. You can also use this action to navigate in a form according to certain conditions. For example, if the user enters No in a Married control on a health insurance form, the focus can automatically skip the Spouse Name control and move to the next control.

Setting

The GoToControl action uses the following argument.

Action argument	Description

Control Name	The name of the field or control where you want the focus. This is a required argument.

Note   Enter only the name of the field or control in the Control Name argument, not the fully qualified identifier, such as Forms!Products![Product ID].

Remarks

You can't use the GoToControl action to move the focus to a control on a hidden form.

Tip   You can use the GoToControl action to move to a subform, which is a type of control. You can then use the GoToRecord action to move to a particular record in the subform. You can also move to a control on a subform by using the GoToControl action to move first to the subform and then to the control on the subform.

To run the GoToControl action in Visual Basic, use the GoToControl method of the DoCmd object. You can also use the SetFocus method to move the focus to a control on a form or any of its subforms, or to a field in an open table, query, or form datasheet.


GoToPage Action

You can use the GoToPage action to move the focus in the active form to the first control on a specified page. You can use this action if you have created a form with page breaks that contains groups of related information. For example, you might have an Employees form with personal information on one page, office information on another page, and sales information on a third page. You can use the GoToPage action to move to the desired page.

Setting

The GoToPage action uses the following arguments.

Action argument	Description

Page Number	The number of the page to which you want to move the focus. If you leave this argument blank, the focus stays on the current page. You can use the Right and Down arguments to display the part of the page you want to see.

Right	The current horizontal position of the spot on the page, measured from the left edge of its containing window, that is to appear at the left edge of the window. This is required if you specify a Down argument.

Down	The current vertical position of the spot on the page, measured from the top edge of its containing window, that is to appear at the top edge of the window. This is required if you specify a Right argument.

Note   The Right and Down measurements are in inches or centimeters, depending on the units set for Measurement system on the Number tab of the Regional Settings Properties dialog box in the Microsoft Windows Control Panel.

Remarks

You can use this action to select the first control (as defined by the form's tab order) on the specified page. Use the GoToControl action to move to a particular control on the form.

You can use the Right and Down arguments for forms with pages larger than the Microsoft Access window. Use the Page Number argument to move to the desired page, and then use the Right and Down arguments to display the part of the page you want to see.

You can't use the GoToPage action to move the focus to a page on a hidden form.

To run the GoToPage action in Visual Basic, use the GoToPage method of the DoCmd object.


GoToRecord Action

You can use the GoToRecord action to make the specified record the current record in an open table or form recordset or query result set.

Setting

The GoToRecord action uses the following arguments.

Action argument	Description

Object Type	The type of object that contains the record you want to make current. You can click Table, Query, or Form in the Object Type box in the Action Arguments section of the Macro window. Leave this box blank to select the active object.

Object Name	The name of the object that contains the record you want to make the current record. The Object Name box shows all objects in the current database of the type selected with the Object Type argument. If you left the Object Type box blank, leave this box blank also.

Record	The record to make the current record. Click Previous, Next, First, Last, Go To, or New from the Record box. The default is Next.

Offset	An integer or expression, which is preceded by an equal sign (=) that evaluates to an integer. This argument specifies the record to make the current record. You can use Offset in two ways:

When the Record argument is Next or Previous, Microsoft Access moves the number of records forward or backward specified in the Offset argument.

When the Record argument is Go To, Microsoft Access moves to the record with the number equal to the Offset argument. The record number is shown in the record number box at the bottom of the screen.

Note   If you click First, Last, or New for Record, Microsoft Access ignores any Offset number. If you enter an Offset number that is too large, Microsoft Access displays an error message. You can't enter negative Offset numbers.

Remarks

If the focus is in a particular control in a record, this action leaves it in the same control for the new record.

You can use the New setting for the Record argument to move to the blank record at the end of a form or table so you can enter new data.

This action is similar to choosing the Go To command from the Edit menu. The First, Last, Next, Previous, and New subcommands of the Go To command have the same effect on the selected object as the First, Last, Next, Previous, and New settings for the Record argument. You can also move to records using the navigation buttons at the bottom of the window.

You can use the GoToRecord action to make a record on a hidden form the current record if you specify the hidden form in the Object Type and Object Name arguments.

To run the GoToRecord action in Visual Basic, use the GoToRecord method of the DoCmd object.


Hourglass Action

You can use the Hourglass action to change the mouse pointer to an image of an hourglass (or another icon you've chosen) while a macro is running. This action can provide a visual indication that the macro is running. This is especially useful when a macro action or the macro itself takes a long time to run.

Setting

The Hourglass action uses the following argument.

Action argument	Description

Hourglass On	Select Yes to display the icon. Click No to display the normal mouse pointer. The default is Yes.

Remarks

You often use this action if you've turned echo off using the Echo action. When echo is off, Microsoft Access suspends screen updates until the macro is finished.

Microsoft Access automatically resets Hourglass On to No when the macro finishes running.

Note   In Microsoft Windows 95, the icon shown by this action is the icon you set for Busy in the Pointers tab of the Mouse Properties dialog box in the Windows Control Panel (the default is an animated hourglass). In Windows NT, this is the icon you set for Wait in the Cursors section of the Control Panel (the default is also an hourglass). In either case, you can choose another icon if you want.

To run the Hourglass action in Visual Basic, use the Hourglass method of the DoCmd object.


Maximize Action

You can use the Maximize action to enlarge the active window so that it fills the application window. This action will allow you want to see as much of the object in the active window as possible.

Setting

The Maximize action doesn't use any arguments.

Remarks

This action has the same effect as clicking the Maximize button in the window's upper-right corner or clicking Maximize on the Control menu.

You can use the Restore action to restore a maximized window to its previous size.

Tip   You may need to use the SelectObject action if the window you want to maximize isn't the active window.

To run the Maximize action in Visual Basic, use the Maximize method of the DoCmd object.


Minimize Action

You can use the Minimize action to reduce the active window to an icon at the bottom of the Microsoft Access window.

Setting

The Minimize action doesn't use any arguments.

Remarks

You can use this action to remove a window from the screen while leaving the object open. You can also use this action to open an object without displaying its window. To display the object, use the SelectObject action with either the Maximize or Restore action. The Restore action restores a minimized window to its previous size.

The Minimize action has the same effect as clicking the Minimize button in the window's upper-right corner or clicking Minimize on the Control menu.

Tips

You may first need to use the SelectObject action if the window you want to minimize isn't the active window.

To minimize the Database window, use the SelectObject action with the In Database Window argument set to Yes and then use the Minimize action.

You can use the Hide command on the Window menu to hide the active window. Instead of being reduced to an icon, the window becomes invisible. The Unhide command on the Window menu will make the window reappear. You can use the DoMenuItem action to carry out either of these commands from a macro.

You can also use the SetValue action to set a form's Visible property to hide or show the form's window.

To run the Minimize action in Visual Basic, use the Minimize method of the DoCmd object.


MoveSize Action

You can use the MoveSize action to move or resize the active window.

Setting

The MoveSize action uses the following arguments.

Action argument	Description

Right	The new horizontal position of the window's upper-left corner, measured from the left edge of its containing window.

Down	The new vertical position of the window's upper-left corner, measured from the top edge of its containing window.

Width	The window's new width.

Height	The window's new height.

If you leave an argument blank, Microsoft Access uses the window's current setting.

You must enter a value for at least one argument.

Note   Each measurement is in inches or centimeters, depending on the units set for Measurement system in the Number tab of the Regional Settings Properties dialog box in the Microsoft Windows Control Panel.

Remarks

This action is similar to clicking Move or Size on the window's Control menu. With the menu commands, you use the keyboard's arrow keys to move or resize the window. With the MoveSize action, you enter the position and size measurements directly. You can also use the mouse to move and size windows.

You can use this action on any window, in any view.

Tips

To move a window without resizing it, enter values for Right and Down argument but leave Width and Height arguments blank.

To resize a window without moving it, enter values for Width and Height arguments but leave Right and Down arguments blank.

To run the MoveSize action in Visual Basic, use the MoveSize method of the DoCmd object.


MsgBox Action

You can use the MsgBox action to display a message box containing a warning or an informational message. For example, you can use the MsgBox action with validation macros. When a control or record fails a validation condition in the macro, a message box can display an error message and provide instructions about the kind of data that should be entered.

Setting

The MsgBox action uses the following arguments.

Action argument	Description

Message	The text in the message box. You can type up to 256 characters or enter an expression (preceded by an equal sign).

Beep	Specifies whether your computer's speaker sounds a beep tone once when the message displays. Click Yes to sound the speaker once. Click No if you don't want a beep. The default is Yes.

Type	The type of message box. Each type has a different icon. Click None, Critical, Warning?, Warning!, or Information. The default is None.

Title	The text displayed in the message box title bar. For example, you can have the title bar display "Customer ID Validation". If you leave this argument blank, "Microsoft Access" is displayed.

Remarks

You can use the MsgBox action to create a formatted error message similar to built-in error messages displayed by Microsoft Access. The MsgBox action permits you to supply a message in three sections for the Message argument. You separate the sections with the "@" character.

The following example displays a formatted message box with a sectioned message. The first section of text in the message is displayed as a bold heading. The second section is displayed as plain text beneath that heading. The third section is displayed as plain text beneath the bold heading "Solution", which is provided for you.

Enter the following in the Message argument:

Wrong button!@This button doesn't work.@Try another.

Microsoft Windows 95 and Windows NT display slightly different icons for the Type argument settings.

You can't run the MsgBox action in Visual Basic. Use the MsgBox function instead.


OpenForm Action

You can use the OpenForm action to open a form in Form view, form Design view, Print Preview, or Datasheet view. You can select data entry and window modes for the form and restrict the records the form displays.

Setting

The OpenForm action uses the following arguments.

Action argument	Description

Form Name	The name of the form to open. The Form Name box in the Action Arguments section of the Macro window shows all forms in the current database. This is a required argument.

If you run a macro containing the OpenForm action in a library database, Microsoft Access looks for the form with this name first in the library database, then in the current database.

View	The view in which the form will open. Click Form, Design, Print Preview, or Datasheet from the View box. The default is Form.

Note   The View argument setting overrides the settings of the form's DefaultView and ViewsAllowed properties. For example, if a form's ViewsAllowed property is set to Datasheet, you can still use the OpenForm action to open the form in Form view.

Filter Name	A filter that restricts or sorts the form's records. You can enter the name of either an existing query or a filter that was saved as a query. However, the query must include all the fields in the form you are opening or have its OutputAllFields property set to Yes.

Where Condition	A valid SQL WHERE clause (without the word WHERE) or expression that Microsoft Access uses to select records from the form's underlying table or query. If you select a filter with the Filter Name argument, Microsoft Access applies this WHERE clause to the filter.

To open a form and restrict its records to those specified by the value of a control on another form, use the following expression.

[fieldname] = Forms![formname]![controlname on other form]

The fieldname argument is the name of a field in the underlying table or query of the form you want to open. The controlname on other form argument is the name of the control on the other form that contains the value you want records in the first form to match.

Note   The maximum length of the Where Condition argument is 256 characters. If you need to enter a more complex SQL WHERE clause longer than this, use the OpenForm method of the DoCmd object in Visual Basic instead. You can enter SQL WHERE clause statements of up to 32,768 characters in Visual Basic.

Data Mode	The data entry mode for the form. This applies only to forms opened in Form view or Datasheet view. Click Add (the user can add new records but can't edit existing records), Edit (the user can edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Note   The Data Mode argument setting overrides the settings of the form's AllowEdits, AllowDeletions, AllowAdditions, and DataEntry properties. For example, if a form's AllowEdits property is set to No, you can still use the OpenForm action to open the form in Edit mode.

Window Mode	The window mode in which the form opens. Click Normal (the form is in the mode set by its properties), Hidden (the form is hidden), Icon (the form opens minimized as an icon at the bottom of the screen), or Dialog (the form's Modal and PopUp properties are set to Yes). The default is Normal.

Remarks

This action is similar to choosing the Open button or Design button in the Database window after selecting a form in the Forms tab.

A form can be modal (it must be closed or hidden before the user can perform any other action) or modeless (the user can move to other windows while the form is open). It can also be a pop-up form (a form used to collect or display information that remains on top of all other Microsoft Access windows). You set the Modal and PopUp properties when you design the form. If you click Normal for the Window Mode argument, the form opens in the mode specified by these property settings. If you click Dialog for the Window Mode argument, these properties are both set to Yes. A form opened as hidden or as an icon returns to the mode specified by its property settings when you show or restore it.

When you open a form with the Window Mode argument set to Dialog, Microsoft Access suspends the macro until the form is closed or hidden. You can hide a form by setting its Visible property to No using the SetValue action.

Tip   You can select a form in the Database window and drag it to a macro action row. This automatically creates an OpenForm action that opens the form in Form view.

Switching to Design view while the form is open removes most of the argument settings for the form, such as the Data Mode and Window Mode argument settings. They aren't in effect even if the user returns to Form view or Datasheet view.


OpenQuery Action

You can use the OpenQuery action to open a select or crosstab query in Datasheet view, Design view, or Print Preview. This action runs an action query. You can also select a data entry mode for the query.

Setting

The OpenQuery action uses the following arguments.

Action argument	Description

Query Name	The name of the query to open. The Query Name box in the Action Arguments section of the Macro window shows all queries in the current database. This is a required argument.

If you run a macro containing the OpenQuery action in a library database, Microsoft Access looks for the query with this name first in the library database, then in the current database.

View	The view in which the query will open. Click Datasheet, Design, or Print Preview in the View box. The default is Datasheet.

Data Mode	The data entry mode for the query. This applies only to queries opened in Datasheet view. Click Add (the user can add new records but can't edit existing records), Edit (the user can edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Remarks

If you click Datasheet for the View argument, Microsoft Access displays the result set if the query is a select, crosstab, union, or pass-through query whose ReturnsRecords property is set to Yes; and it runs the query if it's an action, data-definition, or pass-through query whose ReturnsRecords property is set to No.

The OpenQuery action is similar to choosing the Open button or Design button in the Database window after selecting a query in the Queries tab. With this action you can select additional options.

Tip   You can select a query in the Database window and drag it to a macro action row. This automatically creates an OpenQuery action that opens the query in Datasheet view.

Switching to Design view while the query is open removes the Data Mode argument setting for the query. This setting isn't in effect even if the user returns to Datasheet view.

Tip   If you don't want to display the system messages that normally appear when an action query is run (indicating it is an action query and showing how many records will be affected), you can use the SetWarnings action to suppress the display of these messages.

To run the OpenQuery action in Visual Basic, use the OpenQuery method of the DoCmd object.


OpenReport Action

The OpenReport action opens a report in Design view or Print Preview, or it prints the report immediately. You can also restrict the records that are printed in the report.

Setting

The OpenReport action uses the following arguments.

Action argument	Description

Report Name	The name of the report to open. The Report Name box in the Action Arguments section of the Macro window shows all reports in the current database. This is a required argument.

If you run a macro containing the OpenReport action in a library database, Microsoft Access looks for the report with this name first in the library database, then in the current database.

View	The view in which the report will open. Click Print (to print the report immediately), Design, or Print Preview in the View box. The default is Print Preview.

Filter Name	A filter that restricts the report's records. You can enter the name of either an existing query or a filter that was saved as a query. However, the query must include all the fields in the report you are opening or have its OutputAllFields property set to Yes.

Where Condition	A valid SQL WHERE clause (without the word WHERE) or expression that Microsoft Access uses to select records from the report's underlying table or query. If you select a filter with the Filter Name argument, Microsoft Access applies this WHERE clause to the filter.

To open a report and restrict its records to those specified by the value of a control on a form, use the following expression.

[fieldname] = Forms![formname]![controlname on form]

The fieldname argument is the name of a field in the underlying table or query of the report you want to open. The controlname on form argument is the name of the control on the form that contains the value you want records in the report to match.

Note   The maximum length of the Where Condition argument is 256 characters. If you need to enter a more complex SQL WHERE clause longer than this, use the OpenForm method of the DoCmd object in Visual Basic instead. You can enter SQL WHERE clause statements of up to 32,768 characters in Visual Basic.

Remarks

The Print setting for the View argument prints the report immediately using the current printer settings without bringing up the Print dialog box. You can also use the OpenReport action to open and set up a report and then use the PrintOut action to print it. For example, you may want to modify the report or use the PrintOut action to change the printer settings before you print.

The OpenReport action is similar to clicking the Design button, the Preview button, or the Print command on the File menu in the Database window after selecting a report.

Tips

To print similar reports for different sets of data, use a filter or a WHERE clause to restrict the records printed in the report. Then edit the macro to apply a different filter or change the Where Condition argument.

You can select a report in the Database window and drag it to a macro action row. This automatically creates an OpenReport action that opens the report in Print Preview.


OpenTable Action

You can use the OpenTable action to open a table in Datasheet view, Design view, or Print Preview. You can also select a data entry mode for the table.

Setting

The OpenTable action uses the following arguments.

Action argument	Description

Table Name	The name of the table to open. The Table Name box in the Action Arguments section of the Macro window shows all tables in the current database. This is a required argument.

If you run the macro containing the OpenTable action in a library database, Microsoft Access looks for the table with this name first in the library database, then in the current database.

View	The view in which the table will open. Click Datasheet, Design, or Print Preview from the View box. The default is Datasheet.

Data Mode	The data entry mode for the table. This applies only to tables opened in Datasheet view. Click Add (the user can add new records but can't edit existing records), Edit (the user can edit existing records and add new records), or Read Only (the user can only view records). The default is Edit.

Remarks

This action is similar to clicking the Open button or Design button in the Database window after selecting a table in the Tables tab.

Tip   You can select a table in the Database window and drag it to a macro action row. This automatically creates an OpenTable action that opens the table in Datasheet view.

Switching to Design view while the table is open removes the table's Data Mode argument setting. This setting won't be in effect even if the user returns to Datasheet view.

To run the OpenTable action in Visual Basic, use the OpenTable method of the DoCmd object.


PrintOut Action

You can use the PrintOut action to print the active object in the open database. You can print datasheets, reports, forms, and modules.

Setting

The PrintOut action uses the following arguments.

Action argument	Description

Print Range	The range to print. Click All (the user can print all of the object), Selection (the user can print the part of the object that is selected), Pages (the user can specify a range of pages in the Page From and Page To arguments). The default is All.

Page From	The first page to print. Printing starts at the top of this page. This argument is required if you click Pages in the Print Range box.

Page To	The last page to print. Printing stops at the bottom of this page. This argument is required if you click Pages for the Print Range box.

Print Quality	The print quality. Click High, Medium, Low, or Draft. The lower the quality, the faster the object prints. The default is High.

Copies	The number of copies to print. The default is 1.

Collate Copies	Click Yes to collate the printed copies. Click No if you don't need to collate the copies. The object may print faster if this argument is set to No. The default is Yes.

Remarks

This action is similar to selecting an object and then clicking Print on the File menu. With the action, however, no Print dialog box appears.

Tip   If you have particular print settings you use frequently, create a macro containing a PrintOut action with these settings in its arguments.

The arguments for this action correspond to options in the Print dialog box. However, unlike the FindRecord action and Find In Field dialog box, the argument settings aren't shared with the Print dialog box options.

To run the PrintOut action in Visual Basic, use the PrintOut method of the DoCmd object.


Quit Action

You can use the Quit action to exit Microsoft Access. The Quit action can also specify one of several options for saving database objects prior to exiting Microsoft Access.

Setting

The Quit action uses the following argument.

Action argument	Description

Options	Specifies what happens to unsaved objects when you quit Microsoft Access. Click Prompt to display dialog boxes that ask whether to save each object. Click Save All to save all objects without prompting by dialog boxes. Click Exit to quit without saving any objects. The default is Save All.

Remarks

Microsoft Access doesn't run any actions that follow the Quit action in a macro.

You can use this action to quit Microsoft Access without prompts from Save dialog boxes by using a custom menu command or a button on a form. For example, you might have a master form that you use to display the objects in your custom workspace. This form could have a Quit button that runs a macro containing the Quit action with the Options argument set to Save All.

This action has the same effect as choosing the Exit command from the File menu. If you have any unsaved objects when you choose this command, the dialog boxes that appear are the same as those displayed when you select Prompt for the Options argument of the Quit action.

You can use the Save action in a macro to save a specified object without having to quit Microsoft Access or close the object.

To run the Quit action in Visual Basic, use the Quit method of the DoCmd object.


Rename Action

You can use the Rename action to rename a specified database object.

Setting

The Rename action uses the following arguments.

Action argument	Description

New Name	A new name for the database object. This is a required argument.

Object Type	The type of object you want to rename. Click Table, Query, Form, Report, Macro, or Module in the Object Type box in the Action Arguments section of the Macro window. To rename the object selected in the Database window, leave this argument blank.

Old Name	The name of the object to be renamed. The Old Name box shows all objects in the database of the type selected by the Object Type argument. If you leave Object Type blank, leave this argument blank also.

Note   If you run a macro containing the Rename action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

The new name of the database object must follow the standard naming conventions for Microsoft Access objects.

You cannot rename an open object.

If you leave the Object Type and Old Name arguments blank, Microsoft Access renames the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action with the In Database Window argument set to Yes. You can also select an object by clicking it the Database window, clicking it again so you can edit its name, and entering a new name. With the Rename action, you don't have to select the object first in the Database window, and you don't have to stop the macro to enter the new name.

This action differs from the CopyObject action, which creates a copy of the object under a new name.

To run the Rename action in Visual Basic, use the Rename method of the DoCmd object.


RepaintObject Action

You can use the RepaintObject action to complete any pending screen updates for a specified database object or the active database object, if none is specified. Such updates include any pending recalculations for the object's controls.

Setting

The RepaintObject action uses the following arguments.

Action argument	Description

Object Type	The type of object to repaint. Click Table, Query, Form, Report, Macro, or Module from the Object Type box in the Action Arguments section of the Macro window. Leave this argument blank to select the active object.

Object Name	The name of the object to repaint. The Object Name box shows all objects in the database of the type selected by the Object Type argument. If you leave the Object Type argument blank, leave this argument blank also.

Remarks

Microsoft Access waits to complete pending screen updates until it finishes other pending tasks. With this action, you can force immediate repainting of the controls in the specified object. You can use this action:

When you use the SetValue action to change values in a number of controls. Microsoft Access might not show the changes immediately, especially if other controls (such as calculated controls) depend on values in the changed controls.

When you want to make sure that the form you're viewing displays data in all of its controls. For example, controls containing OLE objects don't display their data immediately after you open a form.

This action doesn't cause a requery of the database, so it doesn't show new and changed records, or remove deleted records from the object's underlying table or query. Use the Requery action to requery the source of the object or one of its controls. Use the ShowAllRecords action to display the most recent records and remove any applied filters.

Note   The RepaintObject action doesn't have the same effect as choosing the Refresh command from the Records menu, which shows any changes you or other users have made to the currently displayed records in forms and datasheets.

To run the RepaintObject action in Visual Basic, use the RepaintObject method of the DoCmd object.


Requery Action

You can use the Requery action to update the data in a specified control on the active object by requerying the source of the control. If no control is specified, this action requeries the source of the object itself. Use this action to ensure that the active object or one of its controls displays the most current data.

Setting

The Requery action uses the following argument.

Action argument	Description

Control Name	The name of the control you want to update. You should use only the name of the control, not the fully qualified identifier, such as Forms!formname!controlname. Leave this argument blank to requery the source of the active object. If the active object is a datasheet or a query result set, you must leave this argument blank.

Remarks

The Requery action does one of the following:

Reruns the query on which the control or object is based.

Displays any new or changed records, and removes any deleted records from the table on which the control or object is based.

Controls based on a query or table include:

List boxes and combo boxes.

Subform controls.

OLE objects, such as charts.

Controls containing domain aggregate functions, such as DSum.

If the specified control is not based on a query or table, this action forces a recalculation of the control.

If you leave the Control Name argument blank, the Requery action has the same effect as pressing SHIFT+F9 when the object has the focus. If a subform control has the focus, this action requeries only the source of the subform (just as pressing SHIFT+F9 does).

Note   The Requery action requeries the source of the control or object. In contrast, the RepaintObject action repaints controls in the specified object but doesn't requery the database or display new records. The ShowAllRecords action not only requeries the active object, but it also removes any applied filters, which the Requery action does not do.

If you want to requery a control that is not on the active object, you must use the Requery method in Visual Basic, not the Requery action or its corresponding Requery method of the DoCmd object. The Requery method in Visual Basic is faster than the Requery action or the DoCmd Requery method. In addition, when you use the Requery action or the DoCmd Requery method, Microsoft Access closes the query and reloads it from the database, but when you use the Requery method, Microsoft Access reruns the query without closing and reloading it. Note that the data access Requery method works the same way as the Microsoft Access Requery method.


Restore Action

You can use the Restore action to restore a maximized or minimized window to its previous size.

Setting

The Restore action doesn't use any arguments.

Remarks

This action works on the selected object. If an object has been minimized to an icon, you can first select it using the SelectObject action and then restore it to its previous size using the Restore action.

You can use the MoveSize action to move or size a window that you have restored.

The Restore action has the same effect as clicking the Restore button in the window's upper-right corner or clicking the Restore command on the window's Control menu.

To run the Restore action in Visual Basic, use the Restore method of the DoCmd object.


RunApp Action

You can use the RunApp action to run a Microsoft Windows-based or MS-DOS–based application, such as Microsoft Excel, Microsoft Word for Windows, or Microsoft PowerPoint, from within Microsoft Access. For example, you may want to paste or link Microsoft Excel spreadsheet data into your Microsoft Access database.

Setting

The RunApp action uses the following argument.

Action argument	Description

Command Line	The command line used to start the application (including the path name and any other necessary parameters, such as switches that run the application in a particular mode). This is a required argument.

Remarks

The application selected with this action loads and runs in the foreground. The macro containing this action continues to run.

You can transfer data between the other application and Microsoft Access by using the Windows dynamic data exchange (DDE) facility or the Clipboard. You can use the SendKeys action to send keystrokes to the other application (although DDE is a more efficient method for transferring data). You can also share data among applications using OLE Automation.

MS-DOS–based applications run in an MS-DOS window within the Windows environment.

This action has the same effect as double-clicking a program icon in a Windows program group or running a program from the Run dialog box in the Windows Program Manager. In Windows 95, there are a number of ways to start an application, including starting the program from the Windows Explorer, using the Run command on the Start menu, and double-clicking a program icon on the Windows Desktop.

You can't run the RunApp action in Visual Basic. Use the Visual Basic Shell function instead.


RunCode Action

You can use the RunCode action to run a Visual Basic Function procedure.

Setting

The RunCode action uses the following argument.

Action argument	Description

Function Name	The name of the Visual Basic Function procedure to execute. Put any function arguments in parentheses. This is a required argument.

Note   To use the Expression Builder to select a function for this argument, click the Build button to the right of the Function Name box. Click a function in the list in the Expression Builder.

Remarks

The user-defined Function procedures are stored in Microsoft Access modules.

You must include parentheses, even if the Function procedure doesn't have any arguments, as in the following example.

TestFunction()

Unlike user-defined function names used for event property settings, the function name in the Function Name argument does not begin with an equal sign (=).

Microsoft Access ignores the return value of the function.

Tip   To run a Sub procedure or event procedure written in Visual Basic, create a Function procedure that calls the Sub procedure or event procedure. Then use the RunCode action to run the Function procedure.

If you use the RunCode action to call a function, Microsoft Access looks for the function with the name specified by the Function Name argument in the standard modules for the database. However, when this action runs in response to choosing a menu command on a form or report or in response to an event on a form or report, Microsoft Access looks for the function first in the form or report module and then in the standard modules.

This action isn't available in Visual Basic. Run the desired Function procedure directly in Visual Basic.


RunMacro Action

You can use the RunMacro action to run a macro. The macro can be in a macro group.

You can use this action to:

Run a macro from within another macro.

Run a macro based on a certain condition.

Attach a macro to a custom menu command.

Setting

The RunMacro action uses the following arguments.

Action argument	Description

Macro Name	The name of the macro to run. The Macro Name box in the Action Arguments section of the Macro window shows all macros (and macro groups) in the current database. If the macro is in a macro group, it is listed under the macro group name in the list as macrogroupname.macroname. This is a required argument.

If you run a macro containing the RunMacro action in a library database, Microsoft Access looks for the macro with this name in the library database and doesn't look for it in the current database.

Repeat Count	The maximum number of times the macro will run. If you leave this argument blank (and the Repeat Expression argument is also blank), the macro runs once.

Repeat Expression	An expression that evaluates to True (-1) or False (0). The macro stops running if the expression evaluates to False. The expression is evaluated each time the macro runs.

Remarks

If you enter a macro group name for the Macro Name argument, Microsoft Access runs the first macro in the macro group.

This action is similar to clicking Macro on the Tools menu, which runs a specified macro. However, the command runs the macro only once, whereas the RunMacro action can run a macro as many times as you want.

Tip   You can use the Repeat Count and Repeat Expression arguments to determine how many times the macro runs:

If you leave both arguments blank, the macro runs once.

If you enter a number for Repeat Count but leave Repeat Expression blank, the macro runs the specified number of times.

If you leave Repeat Count blank but enter an expression for Repeat Expression, the macro runs until the expression evaluates to False.

If you enter values for both arguments, the macro runs the number of times specified in Repeat Count or until Repeat Expression evaluates to False, whichever occurs first.

When you run the original macro, and it reaches the RunMacro action, Microsoft Access runs the called macro. When the called macro has finished, Microsoft Access returns to the original macro and performs the next action.

Notes

You can call a macro in the same macro group or in another macro group.

You can nest macros. That is, you can run macro A, which in turn calls macro B, and so on. In each case, when the called macro has finished, Microsoft Access returns to the macro that called it and runs the next action in that macro.

To run the RunMacro action in Visual Basic, use the RunMacro method of the DoCmd object.


SelectObject Action

You can use the SelectObject action to select a specified database object.

Setting

The SelectObject action uses the following arguments.

Action argument	Description

Object Type	The type of database object to select. Click Table, Query, Form, Report, Macro, or Module from the Object Type box in the Action Arguments section of the Macro window. This is a required argument.

Object Name	The name of the object to select. The Object Name box shows all objects in the database of the type selected by the Object Type box. This is a required argument.

In Database Window	Determines whether Microsoft Access selects the object in the Database window. Click Yes to select the object or No not to select the object in the Database wndow. The default is No.

Remarks

The SelectObject action works with any Microsoft Access object that can receive the focus. This action gives the specified object the focus and shows the object if it is hidden. If the object is a form, the SelectObject action sets the form's Visible property to Yes and returns the form to the mode set by its form properties (for example, as a modal or pop-up form).

If the object isn't open in one of the other Microsoft Access windows, you can select it in the Database window by setting the In Database Window argument to Yes. If you set the In Database Window argument to No, an error message appears when you try to select an object that isn't open.

Often, you might use this action to select an object on which you want to perform additional actions. For example, you may want to restore an object that has been minimized (using the Restore action) or maximize a window that contains an object you want to work with (using the Maximize action).

If you select a form, you can use the GoToControl, GoToRecord, and GoToPage actions to move to specific areas on the form. The GoToRecord action also works for datasheets.

To run the SelectObject action in Visual Basic, use the SelectObject method of the DoCmd object.


SendKeys Action

You can use the SendKeys action to send keystrokes directly to Microsoft Access or to an active Microsoft Windows-based application.

Setting

The SendKeys action uses the following arguments.

Action argument	Description

Keystrokes	The keystrokes you want Microsoft Access or the application to process. You can type up to 256 characters. This is a required argument.

Wait	Specifies whether the macro should pause until the keystrokes have been processed. Click Yes to pause or No not to pause. The default is No.

Remarks

Microsoft Access processes the keystrokes it receives through the SendKeys action exactly as if you had typed them directly in a Microsoft Access window.

To specify the keystrokes, use the same syntax as the SendKeys statement.

You can use this action to enter information in a dialog box, particularly if you don't want to interrupt the macro to respond manually to the dialog box. Some Microsoft Access actions, such as Print and FindRecord, automatically select the options in certain frequently used dialog boxes. You can use the SendKeys action to select the options in less commonly used dialog boxes.

Notes

Because the dialog box suspends the macro, you must put the SendKeys action before the action that causes the dialog box to open and set the Wait argument to No to avoid breaks in the processing.

The timing of the keystrokes reaching Microsoft Access or another application can be tricky. As a result, it's recommended that if there is some other method (such as the FindRecord action) you can use to achieve a desired task, use that method rather than using the SendKeys action to fill in the options in a dialog box.

If you want to send more than 256 characters to Microsoft Access or another Windows-based application, you can use several SendKeys actions in succession in a macro.

Using the SendKeys action to send keystrokes triggers the appropriate KeyDown, KeyUp, and KeyPress events. Sending non-ANSI keystrokes (such as a function key) doesn't trigger the KeyPress event.

This action isn't available from Visual Basic. Use the SendKeys statement instead.


SetValue Action

You can use the SetValue action to set the value of a Microsoft Access field, control, or property on a form, a form datasheet, or a report.

Setting

The SetValue action uses the following arguments.

Action argument	Description

Item	The name of the field, control, or property whose value you want to set. You must use the full syntax to refer to this item, such as controlname (for a control on the form or report from which the macro was called) or Forms!formname!controlname. This is a required argument.

Expression	The expression Microsoft Access uses to set the value for this item. You must always use the full syntax to refer to any objects in the expression. For example, to increase the value in a Salary control on an Employees form by 10 percent, use Forms!Employees!Salary*1.1. This is a required argument.

Note   You shouldn't use an equal sign (=) before the expression in this argument. If you do, Microsoft Access evaluates the expression and then uses this value as the expression in this argument. This can produce unexpected results if the expression is a string.

For example, if you type ="String1" for this argument, Microsoft Access first evaluates the expression as String1. Then it uses String1 as the expression in this argument, expecting to find a control or property named String1 on the form or report that called the macro.

Note   To use the Expression Builder to create an expression for either of these action arguments, click the Build button to the right of the Expression box.

Remarks

You can use this action to set a value for a field or control on a form, a form datasheet, or a report. You can also set the value for almost all control, form, and report properties in any view. To find out whether a particular property can be set using a macro and which views it can be set in, see the topic for that property.

You can also set the value for a field in a form's underlying table even if the form doesn't contain a control bound to the field. Use the syntax Forms!formname!fieldname in the Item box to set the value for such a field. You can also refer to a field in a report's underlying table using the syntax Reports!reportname!fieldname, but there must be a control on the report bound to this field, or the field must be referred to in a calculated control on the report.

If you set the value of a control on a form, the SetValue action doesn't trigger the control's form-level validation rules, but it does trigger the underlying field's table-level validation rules if the control is a bound control. The SetValue action also triggers recalculation, but the recalculation may not happen immediately. To trigger immediate repainting and force the recalculation to completion, use the RepaintObject action. The value you set in a control using the SetValue action is also not affected by an input mask set in the control's or underlying field's InputMask property.

To change the value of a control, you can use the SetValue action in a macro specified by the control's AfterUpdate event property. However, you can't use the SetValue action in a macro specified by a control's BeforeUpdate event property to change the value of the control (although you can use SetValue to change the value of other controls). You can also use SetValue in a macro specified by the BeforeUpdate or AfterUpdate property of a form to change the value of any controls in the current record.

Note   You can't use the SetValue action to set the value of the following controls:

Bound controls and calculated controls on reports.

Calculated controls on forms.

Tip   You can use the SetValue action to hide or show a form in Form view. Enter Forms!formname.Visible in the Item box and No or Yes in the Expression box. Setting a modal form's Visible property to No hides the form and makes it modeless. Setting the property to Yes displays the form and makes it modal again.

Changing the value of or adding new data in a control using the SetValue action in a macro does not trigger events such as BeforeUpdate, BeforeInsert, or Change that occur when you change or enter data in these controls in the user interface. These events also don't occur if you set the value of the control using Visual Basic.

This action isn't available in Visual Basic. Set the value directly in Visual Basic.


SetWarnings Action

You can use the SetWarnings action to turn system messages on or off.

Setting

The SetWarnings action uses the following argument.

Action argument	Description

Warnings On	Specifies whether system messages are displayed. Click Yes to turn on system messages or No not to turn on system messages. The default is No.

Remarks

You can use this action to prevent modal warnings and message boxes from stopping the macro. However, error messages are always displayed. Also, Microsoft Access displays any dialog boxes that require input other than just choosing a button (such as OK, Cancel, Yes, or No) [image] for example, any dialog box that requires you to enter text or select one of several options.

This action has the same effect as pressing ENTER whenever a warning or message box is displayed. Typically, an OK or Yes is chosen in response to the warning or message.

When the macro finishes, Microsoft Access automatically turns the display of the system messages back on.

Often, you'll use this action with the Echo action, which hides the results of a macro until it is finished. You can use the SetWarnings action to hide the warnings and message boxes as well.

Caution   Although the SetWarnings action can simplify interactions with macros, you must be careful about turning system messages off. In some situations, you won't want to continue a macro if a certain warning message is displayed. Unless you're confident of the outcome of all macro actions, you should avoid using this action.

To run the SetWarnings action in Visual Basic, use the SetWarnings method of the DoCmd object.


ShowAllRecords Action

You can use the ShowAllRecords action to remove any applied filter from the active table, query result set, or form, and display all records in the table or result set or all records in the form's underlying table or query.

Setting

The ShowAllRecords action doesn't use any arguments.

Remarks

Use this action to ensure that all records (including any changed or new records) are displayed for a table, query result set, or form. This action causes a requery of the records for a form or subform.

You can also use this action to remove any filter that was applied with the ApplyFilter action, the Apply Filter/Sort command on the Records menu, or the Filter Name or Where Condition argument of the OpenForm action.

This action has the same effect as clicking Remove Filter/Sort on the Records menu or clicking the Remove Filter button on the toolbar in Form view or Datasheet view.

To run the ShowAllRecords action in Visual Basic, use the ShowAllRecords method of the DoCmd object.


StopAllMacros Action

You can use the StopAllMacros action to stop all nested macros that are currently running.

Setting

The StopAllMacros action doesn't use any arguments.

Remarks

You typically use this action when an error condition makes it necessary to stop all macros. You can use a conditional expression in the macro's action row that contains this action. When the expression evaluates to True (-1), Microsoft Access stops all macros.

For example, you might have a macro that displays a message box as one of a number of complex actions, including running other macros. If the user chooses Cancel in this message box, the StopAllMacros action can stop all the macros that are running.

If a macro has used the Echo or SetWarnings actions to turn echo or the display of system messages off, the StopAllMacros action automatically turns them back on.

This action is not available in Visual Basic.


StopMacro Action

You can use the StopMacro action to stop the currently running macro.

Setting

The StopMacro action doesn't use any arguments.

Remarks

You typically use this action when a condition makes it necessary to stop the macro. You can use a conditional expression in the macro's action row that contains this action. When the expression evaluates to True (-1), Microsoft Access stops the macro.

For example, you might create a macro that opens a form showing the daily order totals for the date entered in a custom dialog box. You could use a conditional expression to be sure that the Order Date control on the dialog box contains a valid date. If it doesn't, the MsgBox action can display an error message and the StopMacro action can stop the macro.

If the macro has used the Echo or SetWarnings actions to turn echo or the display of system messages off, the StopMacro action automatically turns them back on.

This action is not available from Visual Basic.


Save Action

You can use the Save action to save either a specified Microsoft Access object or the active object if none is specified. You can also save the active object with a new name (this functions the same as the Save As command).

Setting

The Save action uses the following arguments.

Action argument	Description
Object Type	The type of object you want to save. Click Table, Query, Form, Report, Macro, or Module in this argument's drop-down list in the Action Arguments section of the Macro window. To select the active object, leave this argument blank. If you select an object type in this argument, you must select an existing object's name in the Object Name argument.
Object Name	The name of the object to be saved. The Object Name box shows all objects in the database of the type selected in the Object Type argument. If you leave the Object Type argument blank, you can leave this argument blank to save the active object, or enter a new name in this argument to save the active object with this name. If you enter a new name, the name must follow the standard naming conventions for Microsoft Access objects.
Remarks

The Save action works on all database objects that the user can explicitly open and save. The specified object must be open for the Save action to have any effect on the object. This action has the same effect as selecting an object and then saving it by clicking Save on the File menu, or clicking the Save button on the toolbar. Leaving the Object Type argument blank and entering a new name in the Object Name argument has the same effect as clicking Save As/Export on the File menu, and entering a new name for the active object. Using the Save action enables you to specify an object to save and to perform a Save As command from a macro.

The Save action, whether it is carried out in a macro run in the current database or in a library database, always saves the specified object or the active object in the database in which the object was created.

If you save the active object with a new name, but the name is the same as the name of an existing object of this type, a dialog box asks if you want to overwrite the existing object. If you've set the Warnings On argument of the SetWarnings action to No, the dialog box isn't displayed and the old object is automatically overwritten.

To run the Save action in Visual Basic, use the Save method of the DoCmd object.


SetMenuItem Action

You can use the SetMenuItem action to set the state of menu items (enabled or disabled, checked or unchecked) on the custom menu bar or global menu bar for the active window.

Setting

The SetMenuItem action uses the following arguments.

Action argument	Description
Menu Index	The index of the menu that contains the command for which you want to set the state. Enter an Integer value, starting from 0, for the index of the desired menu in the custom menu bar or global menu bar for the active window. The index is relative to the menu's position in the menu bar macro for the custom menu bar or global menu bar (the position of this menu's AddMenu action in the menu bar macro, counting from 0). The menu bar's display may be somewhat different, since you can use conditional expressions in the menu bar macro to hide or display custom menu items. This is a required argument. If you select a menu with this argument and leave the Command Index and Subcommand Index arguments blank, you can enable or disable the menu name itself. You can't, however, check or uncheck a menu name (Microsoft Access ignores the Check and Uncheck settings for the Flag argument for menu names).
Command Index	The index of the command for which you want to set the state. Enter an Integer value, starting from 0, for the index of the desired command in the menu selected with the Menu Index argument. The index is relative to the command's position in the macro group that defines the selected menu for the custom menu bar or global menu bar (the position of this command's macro in the macro group, counting from 0). The menu's display may be somewhat different, since you can use conditional expressions in the menu's macro group to hide or display custom menu commands.
Subcommand Index	The index of the subcommand for which you want to set the state. This applies only if the desired command has a submenu. Enter an Integer value, starting from 0, for the index of the desired subcommand in the submenu selected with the Command Index argument. The index is relative to the subcommand's position in the macro group that defines the selected submenu for the custom menu bar or global menu bar (the position of this subcommand's macro in the macro group, counting from 0).
Flag	The state you want to set the command or subcommand to. You can select Gray to disable the command (so it appears dimmed), Ungray to enable it, Check to place a check by the command (typically indicating it has been selected or toggled), or Uncheck to remove the check. The default is Ungray.
Remarks

The SetMenuItem action works only on a custom menu bar or global menu bar for the active window. It does not work on the built-in Microsoft Access menu bars, and if the active window does not have a custom menu bar or global menu bar, running a macro containing the SetMenuItem action causes a run-time error. Note that a global menu bar, if you have defined one, replaces the built-in menu bar for all Microsoft Access windows, except where you have added a custom menu bar for a form or report.

You can use this action to set the state of menu commands and subcommands, but not subcommands of subcommands.

You can use the SetMenuItem action to temporarily set the state of a Microsoft Access menu command (put into the custom menu using the DoMenuItem action). However, as soon as Microsoft Access refreshes the menu, the command returns to its normal state. For example, if you use the SetMenuItem action to disable a custom menu command that maps to the Cut command on the Edit menu, the command is automatically enabled again when you select a piece of text.

To run the SetMenuItem action in Visual Basic, use the SetMenuItem method of the DoCmd object.


Understanding Scope

Scope refers to the availability of a variable, constant, or procedure for use by another procedure. There are three scoping levels: procedure-level, private module-level, and public module-level.

You determine the scope of a variable when you declare it. It's a good idea to declare all variables explicitly to avoid naming-conflict errors between variables with different scopes.

Procedure-Level Scope

A variable or constant defined within a procedure is not recognized outside that procedure. Only the procedure that contains the variable declaration can use it. In the following example, the first procedure displays a message box that contains a string. The second procedure displays a blank message box because the variable strMsg is local to the first procedure.

Sub LocalVariable()

Dim strMsg As String

strMsg = "This variable can't be used outside this procedure."

MsgBox strMsg

End Sub

Sub OutsideScope()

MsgBox strMsg

End Sub

Private Module-Level Scope

You can define module-level variables and constants in the Declarations section of a module. Module-level variables may be either public or private. Public variables are available to all procedures in all modules in the database; private variables are available only to procedures in that module. By default, variables declared with the Dim statement in the Declarations section are scoped as private. However, preceding the variable with the Private keyword makes the scope obvious in your code.

In the following example, the string variable strMsg is available to any procedures defined in the module. When the second procedure is called, it displays the contents of the string variable strMsg in a dialog box.

' Add following to Declarations section of module.

Private strMsg sAs String

Sub InitializePrivateVariable()

strMsg = "This variable can't be used outside this module."

End Sub

Sub UsePrivateVariable()

MsgBox strMsg

End Sub

Note   Public procedures in a standard module are available to any referencing database. To limit the scope of all procedures in a module to the current database, add an Option Private statement to the Declarations section of the module. Public variables and procedures will still be available to other procedures in the current database, but not to referencing databases.

Public Module-Level Scope

If you declare a module-level variable as public, it is available to all procedures in the database. In the following example, the string variable strMsg can be used by any procedure in any module in the database.

' Include in Declarations section of module.

Public strMsg As String

All procedures are public by default, except for event procedures. When Microsoft Access creates an event procedure, the Private keyword is automatically inserted before the procedure declaration. For all other procedures, you must explicitly declare the procedure with the Private keyword if you do not want it to be public.

You can use public procedures, variables, and constants defined in standard modules from referencing databases. However, you must first set a reference to the database in which they are defined. For information about referencing other databases, see Setting References.

Public procedures, variables, and constants defined in form modules or report modules are not available to referencing databases, because these modules are private to the database.


Lifetime of Variables

The time during which a variable retains its value is known as its lifetime. The value of a variable may change over its lifetime, but it maintains some value. When a variable goes out of scope, it no longer has a value.

When a procedure begins running, Microsoft Access initializes all variables that have been declared explicitly. A numeric variable is initialized to zero, a variable-length string is initialized to a zero-length string (" "), and a fixed-length string is filled with the character represented by the ASCII character code 0, or Chr(0). Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

When you declare an object variable, Microsoft Access reserves space for it in memory, but it has no value until you assign an object reference to it using the Set statement.

In most cases your code will change the value of the variable. If the value of a variable is not changed, it retains its initialized value until it goes out of scope.

A procedure-level variable declared with the Dim statement retains a value until the procedure is finished running. If the procedure calls other procedures, the variable retains its value while those procedures are running as well.

If a procedure-level variable is declared with the Static keyword, the variable retains its value as long as code is running in any module. When all code has finished running, the variable loses its scope.

A module-level variable is different than a static variable. It retains its value until you reset its value by clicking the Reset button on the toolbar, or until you close the database. Module-level variables consume memory resources until you reset their values, so use them only when necessary.


Using Arrays in Visual Basic

You can declare an array variable when you need to work with a set of values of the same data type. You can think of an array as a single variable with many compartments to store values, while a typical variable has only one storage compartment in which it can store one value. You can refer to the array as a whole when you need to refer to all the values it holds, or you can refer to its individual elements.

For example, if you have a figure for daily expenses for each day of the year, rather than declaring 365 variables, you can declare one array variable with 365 elements. Each element in an array contains one value. The following statement declares the array variable curExpense with 365 elements. By default, an array is indexed beginning with zero, so the upper bound of the array is 364 rather than 365.

Dim curExpense(364) As Currency

To set the value of an individual element, you specify the element's index. The following example assigns each element in the array an initial value of 20.

Sub FillArray()

Dim curExpense(364) As Currency

Dim intI As Integer

For intI = 0 to 364

curExpense(intI) = 20

Next

End Sub

Changing the Lower Bound

You can use the Option Base statement at the top of a module to change the default index of the first element from 0 to 1. The following example changes the index for the first element, and declares the array variable curExpense with 365 elements.

Option Base 1

Dim curExpense(365) As Currency

You can also explicitly set the lower bound of an array by using a To clause, as shown in the following example.

Dim curExpense(1 To 365) As Currency

Dim strWeekday(7 To 13) As String

Storing Variant Values in Arrays

There are two ways to create arrays of Variant values. One way is to declare an array of the Variant data type, as shown in the following example.

Dim varData(3) As Variant

varData(0) = "Claudia Bendel"

varData(1) = "4242 Maple Blvd"

varData(2) = 38

varData(3) = Format("06-09-1952", "General Date")

The other way is to assign the array returned by the Array function to a Variant variable, as shown in the following example.

Dim varData As Variant

varData = Array("Claudia Bendel", "4242 Maple Blvd", 38, _

Format("06-09-1952", "General Date"))

Note that you identify the elements in an array of Variant values by index, no matter which technique you use to create the array. For example, the following statement could be added to either of the preceding two examples.

MsgBox "Data for " & varData(0) & " has been recorded."

Using Multidimensional Arrays

In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the following statement declares a two-dimensional, 5-by-10 array.

Dim sngMulti(1 To 5, 1 To 10) As Single

Use nested For...Next statements to process multidimensional arrays. The following procedure fills a two-dimensional array with Single values.

Sub FillArrayMulti()

Dim intI As Integer, intJ As Integer

Dim sngMulti(1 To 5, 1 To 10) As Single

' Fill array with values.

For intI = 1 To 5

For intJ = 1 To 10

sngMulti(intI, intJ) = intI * intJ

Debug.Print sngMulti(intI, intJ)

Next intJ

Next intI

End Sub


 Declaring Resizable Arrays in Visual Basic

You can declare a dynamic array if you need to size the array while the code is running. Use the Static, Dim, Private, or Public statement to declare an array, leaving the parentheses empty, as shown in the following example.

Dim sngArray() As Single

Later, in a procedure within the array's scope, use the ReDim statement to change the number of dimensions and to define the number of elements and the upper and lower bounds for each dimension. You can use the ReDim statement to change the dynamic array as often as you need to.

Note   You can use the ReDim statement to declare an array implicitly within a procedure. Be careful not to misspell the name of the array when you use the ReDim statement [image] even if the Option Explicit statement is included in the module, Visual Basic will create a second array.

The following example creates a Recordset object, determines the number of records in the recordset, and fills a dynamic array with the value of the LastName field for each record.

Sub ArrayOfRecords()

' Declare dynamic array.

Dim strNamesArray() As String

Dim dbs As Database, rst As Recordset

Dim intI As Integer

' Return Database variable pointing to current database.

Set dbs = CurrentDb

' Open Recordset object on Employees table.

Set rst = dbs.OpenRecordset("Employees")

' Populate Recordset object.

rst.MoveLast

rst.MoveFirst

' Change number of elements in array.

ReDim strNamesArray(rst.RecordCount - 1)

intI = LBound(strNamesArray)

' Populate array.

Do Until rst.EOF

strNamesArray(intI) = rst!LastName

rst.MoveNext

intI = intI + 1

Loop

End Sub

Preserving Values in Dynamic Arrays

Each time you use the ReDim statement, all the values stored in the array are lost. If you want to retain the existing data, you can use the Preserve keyword. For example, the following statement enlarges the array varArray by 10 elements without losing the current values of the original elements.

ReDim Preserve varArray(UBound(varArray) + 10)

Notes

When you use the Preserve keyword with a dynamic array, you can change only the upper bound of the last dimension.

If you use the Preserve keyword with a dynamic array, you cannot change the number of dimensions.


Saving Space When Creating Arrays

Unless you specify a data type, arrays contain Variant values. Each element in a Variant array occupies a minimum of 16 bytes of memory if it is an array of numbers and 22 bytes if it is an array of characters. By specifying a data type for the elements in an array, you can reduce the amount of memory that the array requires.

' Integer array uses 20 bytes (10 elements * 2 bytes).

Dim intArrayOfIntegers(9) As Integer

' Double-precision array uses 80 bytes (10 elements * 8 bytes).

Dim dblArrayOfDoubles(9) As Double

' Variant array uses at least 160 bytes (10 elements * 16 bytes).

Dim ArrayOfVariants(9) As Variant

For information about how much memory each element in an array of a given data type requires, see Data Type Summary.

The maximum number of elements an array can contain varies depending on the amount of available memory. You are not likely to encounter this limit, but using arrays that exceed the amount of random-access memory available on your system can slow down your code, because the data must then be read from and written to disk.


Error Trapping

You can use the On Error GoTo statement to trap errors and direct procedure flow to the location of error-handling statements within a procedure. For example, the following statement directs the flow to the ErrorHandler label.

On Error GoTo ErrorHandler

Be sure to give each error handler in a procedure a unique name that will not conflict with any other element in the procedure. Within the procedure, place the Exit Sub statement in front of the ErrorHandler label so that the procedure doesn't run the error-checking code if no error occurs.

Sub CausesAnError()

' Direct procedure flow.

On Error GoTo ErrorHandler

' Raise division by zero error.

Err.Raise 11

Exit Sub

ErrorHandler:

' Display error information.

MsgBox "Error number " & Err.Number & ": " & Err.Description

' Resume with statement following occurrence of error.

Resume Next

End Sub

The Raise method of the Err object generates the specified error. The Number property of the Err object returns the number corresponding to the most recent run-time error; the Description property returns the corresponding message text for a given error.

Notes

In previous versions of Microsoft Access, you might have used the Error statement to generate the error, the Err function to return the error number, and the Error function to return a description of the error. Existing error-handling code that relies on the Error statement and the Error function will continue to work. However, it's better to use the Err object and its properties and methods when writing new code.

Previous versions of Microsoft Access returned only one error for all OLE Automation errors. The OLE Automation server application that generated the error now returns the same error information that you would receive if you were working in that application. You may need to rewrite existing error-handling code to handle new OLE Automation errors properly.

If you wish to return the descriptive string associated with a Microsoft Access error or a data access error, but the error has not actually occurred in your code, you can use the AccessError method to return the string.

For more information about setting error traps and writing error-handling statements, see Chapter 8, "Handling Run-Time Errors," in Building Applications with Microsoft Access for Windows 95.


Declaring Variables

When declaring variables, most often you will use a Dim statement. A declaration statement can be placed within a procedure to create a procedure-level variable. Or it may be placed at the top of a module, in the Declarations section, to create a module-level variable.

The following example creates the variable strName and specifies the String data type.

Dim strName As String

If this statement appears within a procedure, the variable strName can be used in that procedure only. If the statement appears in the Declarations section of the module, the variable strName is available to all procedures within the module, but not to procedures in other modules in the database. To make this variable available to all procedures in the database, precede it with the Public statement, as in the following example.

Public strName As String

For information about naming your variables, see Guidelines for naming Visual Basic procedures, variables, and constants.

Variables can be declared as one of the following data types: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, or Variant. If you do not specify a data type, the Variant data type is assigned by default. You can also create a user-defined type using the Type statement. For more information on data types, see the Data Type Summary.

You can declare several variables in one statement. If you want to specify a data type, you need to include the data type for each variable. In the following statement, the variables intX, intY, and intZ are declared as type Integer.

Dim intX As Integer, intY As Integer, intZ As Integer

In the following statement, intX and intY are declared as type Variant; only intZ is declared as type Integer.

Dim intX, intY, intZ As Integer

You don't have to supply the variable's data type in the declaration statement. If you omit the data type, the variable will be of type Variant.

Public Statement

You can use the Public statement to declare public module-level variables.

Public strName As String

Public variables can be used in any procedures in the database. If a public variable is declared in a standard module, it can also be used in any databases that reference the database where the public variable is declared. If a public variable is declared in a form module or report module, it can be used only in procedures in the current database.

Private Statement

You can use the Private statement to declare private module-level variables.

Private MyName As String

Private variables can be used only by procedures in the same module.

Note   The Dim statement, when used at the module level, is equivalent to the Private statement. You may want to use the Private statement to make your code easier to read and interpret.

Static Statement

When you use the Static statement instead of a Dim statement, the declared variable will retain its value between calls. For more information on how variables retain their values, see Lifetime of Variables.

Option Explicit Statement

You can implicitly declare a variable in Visual Basic simply by using it in an assignment statement. However, it's recommended that you explicitly declare all variables. This will reduce the incidence of naming-conflict errors and spelling mistakes. Additionally, all variables that are implicitly declared will be of type Variant. Variables of this type require more memory resources than most other variables. Your application will be more efficient if you declare variables explicitly and with a specific data type.

If you don't want Visual Basic to make implicit declarations, you can place the Option Explicit statement in a module before any procedures. This statement requires you to explicitly declare all variables within the module. If a module includes the Option Explicit statement, a compile-time error will occur when Visual Basic encounters a variable name that has not previously been declared, or that has been spelled incorrectly.

To automatically include the Option Explicit statement in all new modules, click Options on the Tools menu. Click the Modules tab of the Options dialog box, then select the Require Variable Declaration check box in the Coding Options section.

Note   You must explicitly declare fixed arrays and dynamic arrays. For more information on arrays, see Using Arrays in Visual Basic.

Declaring an Object Variable for OLE Automation

When you use Microsoft Access to control another application's objects through OLE Automation, you should set a reference to the other application's type library. Once you've set a reference, you can declare object variables according to their most specific type. For example, when you set a reference to the Microsoft Excel type library, you can declare a variable of type Worksheet from within Microsoft Access to represent a Microsoft Excel Worksheet object.

If you are using another application to control Microsoft Access objects, in most cases you can declare object variables according to their most specific type. You can also use the New keyword to create a new instance of an object automatically. However, you may need to indicate that it is a Microsoft Access object. For example, when you declare an object variable to represent a Microsoft Access form from within Microsoft Visual Basic 4.0, you must distinguish the Microsoft Access Form object from a Microsoft Visual Basic Form object. Include the name of the type library in the variable declaration, as in the following example.

Dim frmOrders As New Access.Form

Some applications, such as Microsoft Excel, don't recognize individual Microsoft Access object types. Even if you set a reference to the Microsoft Access type library from Microsoft Excel, you must declare all Microsoft Access object variables as type Object. Nor can you use the New keyword to create a new instance of the object. The following example shows how to declare a variable to represent an instance of the Microsoft Access Application object from Microsoft Excel. It then creates an instance of the Application object.

Dim appAccess As Object

Set appAccess = CreateObject("Access.Application.7")

To determine which syntax an application supports, see the application's documentation.


Declaring Constants

A constant allows you to assign a meaningful name to a value. After a constant is declared, it cannot be modified or assigned a new value. You use the Const statement to declare a constant and set the value.

You can declare a constant within a procedure or at the top of a module, in the Declarations section. Module-level constants are private by default. To declare a public module-level constant, precede the Const statement with the Public keyword. You can explicitly declare a private constant by preceding the Const statement with the Private keyword to make it easier to read and interpret your code. For more information, see Understanding scope.

The following example declares the public constant conAge as an Integer and assigns it the value 34.

Public Const conAge As Integer = 34

Constants can be declared as one of the following data types: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String, or Variant. Because you already know the value of a constant, you can specify the data type in a Const statement. For more information on data types, see Data Type Summary.

You can declare several constants in one statement. If you want to specify a data type, you need to include the data type for each constant. In the following statement, the constants conAge and conWage are declared as type Integer.

Const conAge As Integer = 34, conWage As Currency = 35000

For information about naming your constants, see Guidelines for naming Visual Basic procedures, variables, and constants.


Calling Procedures with the Same Name

You can call a procedure located in any module in the same database as the active module just as you would call a procedure in the active module. However, if two or more modules contain a procedure with the same name, you need to specify the name of the correct module when you call the procedure. The following example calls the IsLoaded function in the Utility Functions module.

Sub QualifiedByModule()

[Utility Functions].IsLoaded("Orders")

End Sub

If you give the same name to two different procedures in two different databases, you must specify a database name when you call that procedure. For example, in the following procedure, the IsLoaded function is qualified by both the name of the module and the name of the database.

Sub QualifiedByDatabase()

[Northwind.mdb].[Utility Functions].IsLoaded("Orders")

End Sub

To avoid naming conflicts among referenced databases, always give your procedures unique names.


Calling Procedures in a Subform or Subreport

You can call a procedure in a module associated with a subform or subreport in one of two ways. If the form containing the subform is open in Form view, you can refer to the procedure as a method on the subform. The following example shows how to call a procedure ListNames in the Orders Subform, which is bound to a subform control on the Orders form.

Forms!Orders![Orders Subform].Form.ListNames

You can also create a new instance of the form that is being used as a subform, even if neither the main form nor the subform is open, and call the procedure. This will work for any form, whether or not it is being used as a subform. The following example shows how to create an instance of the Orders Subform and call the ListNames procedure.

Dim frm As New [Form_Orders Subform]

frm.ListNames

Note   When you create a new instance of a form with a name consisting of more than one word, enclose the class name of the form in brackets, as shown in the example above.


Eval Function

You can use the Eval function to evaluate an expression that results in a text string or a numeric value.

You can construct a string and then pass it to the Eval function as if the string were an actual expression. The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2.

If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function. For example, Eval("Chr$(65)") returns "A".

Syntax

Eval(stringexpr)

The stringexpr argument is an expression that evaluates to an alphanumeric text string. For example, stringexpr can be a function that returns a string or a numeric value. Or it can be a reference to a control on a form. The stringexpr must evaluate to a string or numeric value; it cannot evaluate to a Microsoft Access object.

Remarks

You can use the Eval function in a calculated control on a form or report, or in a macro or module. The Eval function returns a Variant that is either a string or a numeric type.

The argument stringexpr must be an expression that is stored in a string. If you pass to the Eval function a string that does not contain an numeric expression or a function name but only a simple text string, a run-time error occurs. For example, Eval("Smith") results in an error.

You can use the Eval function to determine the value stored in the Value property of a control. The following example passes a string containing a full reference to a control to the Eval function. It then displays the current value of the control in a dialog box.

Dim ctl As Control, strCtl As String

Set ctl = Forms!Employees!LastName

strCtl = "Forms!Employees!LastName"

MsgBox ("The current value of " & ctl.Name & " is " & Eval(strCtl))

You can use the Eval function to access expression operators that aren't ordinarily available in Visual Basic. For example, you cannot use the SQL operators Between...And or In directly in your code, but you can use them in an expression passed to the Eval function.

The next example determines whether the value of the ShipRegion control on an Orders form is one of several specified state abbreviations. If the field contains one of the abbreviations, intState will be True (-1). Note that you use single quotation marks (') to include one string within another string.

Dim intState As Integer

intState = Eval("Forms!Orders!ShipRegion In " _

& "('AK', 'CA', 'ID', 'WA', 'MT', 'NM', 'OR')")


Eval Function Example

The following example assumes that you have a series of 50 functions defined as A1, A2, and so on. This example uses the Eval function to call each function in the series.

Sub CallSeries()

Dim intI As Integer

For intI = 1 To 50

Eval("A" & intI & "()")

Next intI

End Sub

The next example triggers a Click event as if the user had clicked a button on a form. If the value of the button's OnClick property begins with an equal sign (=), signifying that it is the name of a function, the Eval function calls the function, which is equivalent to triggering the Click event. If the value does not begin with an equal sign, then the value must name a macro. The RunMacro method of the DoCmd object runs the named macro.

Dim ctl As Control, varTemp As Variant
Set ctl = Forms!Contacts!HelpButton
If (Left(ctl.OnClick, 1) = "=") Then
varTemp = Eval(Mid(ctl.OnClick,2))
Else
DoCmd.RunMacro ctl.OnClick
End If


CurrentUser Function

You can use the CurrentUser function to return the name of the current user of the database.

For example, use the CurrentUser function in a procedure that keeps track of the users who modify the database.

Syntax

CurrentUser

Remarks

The CurrentUser function returns a string that contains the name of the current user account.

If you haven't established a secure workgroup, the CurrentUser function returns the name of the default user account, Admin. The Admin user account gives the user full permissions to all database objects.

If you have enabled workgroup security, then the CurrentUser function returns the name of the current user account. User accounts other than Admin may specify permissions that restrict the users' access to database objects.

The following example obtains the name of the current user and displays it in a dialog box.

MsgBox("The current user is: " & CurrentUser)


Actions Grouped by Task

The following table groups actions into categories based on their use.

Category	Task	Action
Data in forms and reports	Restrict data	ApplyFilter
	Move through data	FindNext, FindRecord, GoToControl, GoToPage, GoToRecord
Execution	Carry out a command	DoMenuItem
	Run a macro, procedure, or query	OpenQuery, RunCode, RunMacro, RunSQL
	Run another application	RunApp
	Stop execution	CancelEvent, Quit, StopAllMacros, StopMacro
Import/export	Send Microsoft Access objects to other applications	OutputTo, SendObject
	Transfer data between Microsoft Access and other data formats	TransferDatabase, TransferSpreadsheet, TransferText
Object manipulation	Copy, save, or rename an object	CopyObject, Rename, Save
	Delete an object	DeleteObject
	Move or resize a window	Maximize, Minimize, MoveSize, Restore
	Open or close an object	Close, OpenForm, OpenModule, OpenQuery, OpenReport, OpenTable
	Print an object	OpenForm, OpenQuery, OpenReport, PrintOut
	Select an object	SelectObject
	Set the value of a field, control, or property	SetValue
	Update data or the screen	RepaintObject, Requery, ShowAllRecords
Miscellaneous	Create a custom menu bar for a form	AddMenu, SetMenuItem
	Display information on screen	Echo, Hourglass, MsgBox, SetWarnings
	Generate keystrokes	SendKeys
	Display or hide the toolbar	ShowToolbar
	Sound a beep	Beep


Events and Event Properties Reference

The following reference groups events into categories based on the type of task and lists the events alphabetically.

Grouped by Task

Data Events	Focus Events	Print Events
Error and Timing Events	Keyboard Events	Window Events
Filter Events	Mouse Events
Listed Alphabetically

Event	Event property
Activate	OnActivate
AfterDelConfirm	AfterDelConfirm
AfterInsert	AfterInsert
AfterUpdate	AfterUpdate
ApplyFilter	ApplyFilter
BeforeDelConfirm	BeforeDelConfirm
BeforeInsert	BeforeInsert
BeforeUpdate	BeforeUpdate
Change	OnChange
Click	OnClick
Close	OnClose
Current	OnCurrent
DblClick	OnDblClick
Deactivate	OnDeactivate
Delete	OnDelete
Enter	OnEnter
Error	OnError
Exit	OnExit
Filter	OnFilter
Format	OnFormat
GotFocus	OnGotFocus
KeyDown	OnKeyDown
KeyPress	OnKeyPress
KeyUp	OnKeyUp
Load	OnLoad
LostFocus	OnLostFocus
MouseDown	OnMouseDown
MouseMove	OnMouseMove
MouseUp	OnMouseUp
NoData	OnNoData
NotInList	OnNotInList
Open	OnOpen
Page	OnPage
Print	OnPrint
Resize	OnResize
Retreat	OnRetreat
Timer	OnTimer
Unload	OnUnload
Updated	OnUpdated


Data Events

Data events occur when data is entered, deleted, or changed in a form or control, or when the focus moves from one record to another.

Event	Event property	It occurs
AfterDelConfirm	AfterDelConfirm (forms)	After you confirm record deletions and the records are actually deleted, or after the deletions are canceled.
AfterInsert	AfterInsert (forms)	After a new record is added to the database.
AfterUpdate	AfterUpdate (forms, controls)	After a control or record is updated with changed data. This event occurs when the control or record loses the focus, or you click Save Record on the Records menu. This event occurs for new and existing records.
BeforeDelConfirm	BeforeDelConfirm (forms)	After one or more records are deleted, but before Microsoft Access displays a dialog box asking you to confirm or cancel the deletion. This event occurs after the Delete event.
BeforeInsert	BeforeInsert (forms)	When you type the first character in a new record, but before the record is added to the database.
BeforeUpdate	BeforeUpdate (forms, controls)	Before a control or record is updated with changed data. This event occurs when the control or record loses the focus, or you click Save Record on the Records menu. This event occurs for new and existing records.
Change	OnChange (controls)	When the contents of a text box or the text box portion of a combo box changes; for example, when you type a character in the control or change the Text property of the control using a macro or Visual Basic.
Current	OnCurrent (forms)	When the focus moves to a record, making it the current record, or when you requery a form's source of data. This event occurs when a form is first opened, and whenever the focus leaves one record and moves to another. It also occurs when you requery the source of the data for a form — for example, when you click Remove Filter/Sort on the Records menu, or use the ShowAllRecords action or the Requery action.
Delete	OnDelete (forms)	When a record is deleted, but before the deletion is confirmed and actually performed.
NotInList	OnNotInList (controls)	When a value is entered in a combo box that isn't in the combo box list.
Updated	OnUpdated (controls)	When an OLE object's data has been modified.


Error and Timing Events

The following events are used for error handling and synchronizing data on forms.

Event	Event property	It occurs
Error	OnError (forms)	When a run-time error is produced in Microsoft Access while you are in the form. This includes Microsoft Jet Database Engine errors, but not run-time errors in Visual Basic. (Since macros can't determine what error has occurred, you normally use Visual Basic event procedures with this event.)
Timer	OnTimer (forms)	When a specified time interval passes, as specified by the TimerInterval property of the form. You can use the Timer event to keep data synchronized in a multiuser environment by requerying or refreshing data at specified intervals.


Filter Events

Filter events occur when you apply or create a filter on a form.

Event	Event property	It occurs
ApplyFilter	OnApplyFilter (forms)	When you click Apply Filter/Sort on the Records menu, or click the Apply Filter button on the toolbar. This applies the most recently created filter (created using either the Filter By Form feature or the Advanced Filter/Sort window). When you click the Filter By Selection after pointing to Filter on the Records menu, or click the Filter By Selection button on the toolbar. This applies a filter based on the current selection in the form. When you click Remove Filter/Sort on the Records menu, or click the Remove Filter button on the toolbar. This removes any filter (or sort) currently applied to the form. When you close the Advanced Filter/Sort window or the Filter By Form window.
Filter	OnFilter (forms)	When you click Filter By Form after pointing to Filter on the Records menu, or click the Filter By Form button on the toolbar. This opens the Filter By Form window, where you can quickly create a filter based on the fields in the form. When you click Advanced Filter/Sort after pointing to Filter on the Records menu. This opens the Advanced Filter/Sort window, where you can create complex filters for the form.


Focus Events

Focus events occur when a form or control loses or gains the focus, or a form or report becomes active or inactive.

Event	Event property	It occurs
Activate	OnActivate (forms, reports)	When a form or report becomes the active window.
Deactivate	OnDeactivate (forms, reports)	When a different Microsoft Access window becomes the active window, but before the window becomes the active window. The Deactivate event does not occur when the focus moves to another application's window, a dialog box, or a pop-up form.
Enter	OnEnter (controls)	Before a control actually receives the focus, either from a control on the same form or when the form opens. This event occurs before the GotFocus event.
Exit	OnExit (controls)	Just before a control loses the focus to another control on the same form, This event occurs before the LostFocus event.
GotFocus	OnGotFocus (forms, controls)	When a control, or a form with no active or enabled controls, receives the focus. A form can get the focus only if all visible controls on a form are disabled, or there are no controls on the form.
LostFocus	OnLostFocus (forms, controls)	When a form or control loses the focus. A form can have the focus only if all visible controls on a form are disabled, or there are no controls on the form.


Keyboard Events

Keyboard events occur when you type on a keyboard, or when keystrokes are sent using the SendKeys action or the SendKeys statement.

Event	Event property	It occurs
KeyDown	OnKeyDown (forms, controls)	When you press any key on the keyboard while a control or form has the focus. A form can have the focus only if all visible controls on the form are disabled, or there are no controls on the form. The KeyDown event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic. A form also receives all KeyDown events (even those for controls) before they occur for the controls if you set the form's KeyPreview property to Yes. If you hold down a key, the KeyDown event occurs repeatedly.
KeyPress	OnKeyPress (forms, controls)	When you press and release a key or key combination that produces a standard ANSI character while a control or form has the focus. A form can have the focus only if all visible controls on the form are disabled, or there are no controls on the form. For example, you can use the KeyPress event to respond to keystrokes entered in a text box or combo box. For keystrokes not recognized by KeyPress, such as function keys or navigation keys, use the KeyDown and KeyUp events. The KeyPress event also occurs if you send a keystroke that produces a standard ANSI character to a form or control using the SendKeys action in s macro or the SendKeys statement in Visual Basic. A form also receives all KeyPress events (even those for controls) before they occur for the controls if you set the form's KeyPreview property to Yes. If you hold down a key, the KeyPress event occurs repeatedly.
KeyUp	OnKeyUp (forms, controls)	When you release a pressed key while a control or form has the focus. The object with the focus receives all the keystrokes. A form can have the focus only if all visible controls on the form are disabled, or there are no controls on the form. The KeyUp event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic. A form also receives all KeyUp events (even those for controls) before they occur for the controls if you set the form's KeyPreview property to Yes. If you hold down a key, the KeyUp event occurs after all the KeyDown and KeyPress events have occurred.


Mouse Events

Mouse events occur when a mouse action, such as pressing down or clicking a mouse button, occurs.

Event	Event property	It occurs
Click	OnClick (forms, controls)	For a control, this event occurs when you press and then release (click) the left mouse button on a control. For a form, this event occurs when you click a disabled control or an area outside a section or control.
DblClick	OnDblClick (forms, controls)	When you press and release (click) the left mouse button twice on a control or its label. For a form, this event occurs when you double-click on a blank area or a disabled control on a form.
MouseDown	OnMouseDown (forms, controls)	When you press a mouse button while the pointer is on a form or control. Canceling the MouseDown event using the CancelEvent action in a macro prevents the shortcut menu of a form or control from being displayed when you press the right mouse button.
MouseMove	OnMouseMove (forms, controls)	When you release a pressed mouse button while the pointer is on a form or control.
MouseUp	OnMouseUp (forms, controls)	When you move the mouse pointer over a form, form section, or control.


Print Events

Print events occur when a report is being printed or is being formatted for printing.

Event	Event property	It occurs
Format	OnFormat (reports)	When Microsoft Access determines which data goes in a report section, but before Microsoft Access formats the section for previewing or printing. Your macro or event procedure can use data in the current record to make changes to page layout.
NoData	OnNoData (reports)	After Microsoft Access formats a report for printing that has no data (the report is bound to an empty recordset), but before the report is printed. You can use this event to cancel printing of a blank report.
Page	OnPage (reports)	After Microsoft Access formats a page for printing, but before the page is printed.
Print	OnPrint (reports)	After Microsoft Access has formatted the data in a report section but before the section is printed.
Retreat	OnRetreat (reports)	When Microsoft Access must "back up" past one or more report sections on a page in order to perform multiple formatting passes. This occurs after the section's Format event, but before the Print event. The Retreat event for each section occurs as Microsoft Access backs up past the section. This allows you to undo any changes you have made during the Format event for the section.


Window Events

Window events occur when you open, resize, or close a form or report.

Event	Event property	It occurs
Close	OnClose (forms, reports)	When a form or report is closed and is removed from the screen.
Load	OnLoad (forms)	When a form is opened and its records are displayed. This event occurs before the Current event, but after the Open event.
Open	OnOpen (forms, reports)	When a form is opened but before the first record is displayed. When a report is opened but before it prints.
Resize	OnResize (forms)	When the size of a form changes. This event also occurs when a form is first displayed.
Unload	OnUnload (forms)	When a form is closed and its records are unloaded, but before it's removed from the screen. This event occurs before the Close event.


Statements Reference

The following reference lists alphabetically all the statements (except for SQL statements).

A–D

AppActivate (VBA)	DefByte (VBA)
Beep (VBA)	DefCur (VBA)
Call (VBA)	DefDate (VBA)
ChDir (VBA)	DefDbl (VBA)
ChDrive (VBA)	DefInt (VBA)
Close (VBA)	DefLng (VBA)
Const (VBA)	DefObj (VBA)
Date (VBA)	DefSng (VBA)
DDE	DefStr (VBA)
DDEExecute	DefVar (VBA)
DDEPoke	DeleteControl
DDETerminate	DeleteReportControl
DDETerminateAll	DeleteSetting (VBA)
Declare (VBA)	Dim (VBA)
DefBool (VBA)	Do...Loop (VBA)
E–M

End (VBA)	If...Then...Else (VBA)
Erase (VBA)	Input # (VBA)
Error (VBA)	Kill (VBA)
Exit (VBA)	Let (VBA)
For...Next (VBA)	Line Input # (VBA)
FileCopy (VBA)	Lock (VBA)
Function (VBA)	LSet (VBA)
Get (VBA)	MkDir (VBA)
GoSub...Return (VBA)	Mid (VBA)
GoTo (VBA)
N–R

Name (VBA)	Property Let (VBA)
On Error (VBA)	Property Set (VBA)
On...GoSub (VBA)	Put (VBA)
On...GoTo (VBA)	Randomize (VBA)
Open (VBA)	ReDim (VBA)
Option Base (VBA)	Rem (VBA)
Option Compare (VBA)	Reset (VBA)
Option Explicit (VBA)	Resume (VBA)
Option Private (VBA)	Return (VBA)
Print # (VBA)	RmDir (VBA)
Private (VBA)	RSet (VBA)
Property Get (VBA)
S–Z

SaveSetting (VBA)	Sub (VBA)
Seek (VBA)	Time (VBA)
SelectCase (VBA)	Type (VBA)
SendKeys (VBA)	Unlock (VBA)
Set (VBA)	While...Wend (VBA)
SetAttr (VBA)	Width # (VBA)
Static (VBA)	With (VBA)
Stop (VBA)	Write # (VBA)


Functions Reference

The following reference lists all the functions alphabetically.

A–C

Abs (VBA)	CLng (VBA)
Array (VBA)	CodeDB
Asc (VBA)	Cos (VBA)
AscB (VBA)	CreateControl
Atn (VBA)	CreateObject (VBA)
CBool (VBA)	CreateReport
CByte (VBA)	CSng (VBA)
CCur (VBA)	CStr (VBA)
CDate (VBA)	CurDir (VBA)
CDbl (VBA)	CurrentUser
Choose (VBA)	CVar (VBA)
Chr (VBA)	CVDate (VBA)
CInt (VBA)
D

Date (VBA)	DDERequest
DateAdd (VBA)	DDESend
DateDiff (VBA)	Dir (VBA)
DatePart (VBA)	DLookup
DateSerial (VBA)	DMax
DateValue (VBA)	DMin
DAvg	DoEvents (VBA)
Day (VBA)	DStDev
DCount	DStDevP
DDB (VBA)	DSum
DDE	DVar
DDEInitiate	DVarP
E–G

Environ (VBA)	Fix (VBA)
EOF (VBA)	Format (VBA)
Error (VBA)	FreeFile (VBA)
Eval	FV (VBA)
FileAttr (VBA)	GetObject (VBA)
H–L

Hex (VBA)	IsNumeric (VBA)
Hour (VBA)	IsNull (VBA)
IIf (VBA)	IsObject (VBA)
Input (VBA)	IRR (VBA)
InputBox (VBA)	LBound (VBA)
InStr (VBA)	LCase (VBA)
Int (VBA)	Left (VBA)
IPmt (VBA)	Loc (VBA)
IsDate (VBA)	LOF (VBA)
IsEmpty (VBA)	Log (VBA)
IsMissing (VBA)	LTrim (VBA)
M–R

Max (DAO)	Partition (VBA)
Mid (VBA)	Pmt (VBA)
Min (DAO)	PPmt (VBA)
Minute (VBA)	PV (VBA)
MIRR (VBA)	QBColor (VBA)
Month (VBA)	Rate (VBA)
MsgBox (VBA)	RGB (VBA)
Now (VBA)	Right (VBA)
NPer (VBA)	Rnd (VBA)
NPV (VBA)	RTrim (VBA)
Oct (VBA)
S–T

Second (VBA)	String (VBA)
Seek (VBA)	Sum (DAO)
Sgn (VBA)	Switch (VBA)
Shell (VBA)	SYD (VBA)
Sin (VBA)	SysCmd
SLN (VBA)	Tab (VBA)
Space (VBA)	Tan (VBA)
Spc (VBA)	Time (VBA)
Sqr (VBA)	Timer (VBA)
StDev (DAO)	TimeSerial (VBA)
StDevP (DAO)	TimeValue (VBA)
Str (VBA)	Trim (VBA)
StrComp (VBA)
U–Z

UBound (VBA)	VarP (DAO)
UCase (VBA)	VarType (VBA)
Val (VBA)	Weekday (VBA)
Var (DAO)	Year (VBA)


Methods Reference

The following reference lists all the methods alphabetically.

Grouped by Object or Collection

Application	Form
Collection (VBA)	Group, Groups (DAO)
Container, Containers (DAO)	Index, Indexes (DAO)
Control	Parameter, Parameters (DAO)
Database, Databases (DAO)	Property, Properties (DAO)
DBEngine (DAO)	QueryDef, QueryDefs (DAO)
Debug (VBA)	Recordset, Recordsets (DAO)
DoCmd	Relation, Relations (DAO)
Document, Documents (DAO)	Report
Err (VBA)	TableDef, TableDefs (DAO)
Error (DAO)	User, Users (DAO)
Field, Fields (DAO)	Workspace, Workspaces (DAO)
Listed Alphabetically

A–C

Add (VBA)	CloseCurrentDatabase
AddNew (DAO)	CommitTrans (DAO)
AppendChunk (DAO)	CompactDatabase (DAO)
Append (DAO)	CopyObject
ApplyFilter	CreateDatabase (DAO)
Beep	CreateField (DAO)
BeginTrans (DAO)	CreateGroup (DAO)
BuildCriteria	CreateIndex (DAO)
CancelEvent	CreateProperty (DAO)
CancelUpdate (DAO)	CreateQueryDef (DAO)
Circle	CreateRelation (DAO)
Clear (VBA)	CreateTableDef (DAO)
Clone (DAO)	CreateUser (DAO)
Close	CreateWorkspace (DAO)
Close (DAO)
D–F

DefaultControl	Edit (DAO)
DefaultWorkspaceClone	Execute (DAO)
Delete (DAO)	FieldSize (DAO)
DeleteObject	FillCache (DAO)
DoMenuItem	FindNext (DAO)
Dropdown	FindNext
Echo	FindPrevious (DAO)
Echo (DoCmd)	FindRecord
G–M

GetChunk (DAO)	Line
GetOption	MakeReplica (DAO)
GetRows (DAO)	Maximize
GoToControl	Minimize
GoToPage	Move (DAO)
GoToPage (DoCmd)	MoveFirst (DAO)
GoToRecord	MoveLast (DAO)
Hourglass	MoveNext (DAO)
Idle (DAO)	MovePrevious (DAO)
InsertText	MoveSize
Item (VBA)
N–Q

NewCurrentDatabase	OpenReport
NewPassword (DAO)	OpenTable
OpenCurrentDatabase	OutputTo
OpenDatabase (DAO)	Print (VBA)
OpenForm	PrintOut
OpenModule	PSet
OpenQuery	Quit (DoCmd)
OpenRecordset (DAO)	Quit
R

Raise (VBA)	RepaintObject
Recalc	RepairDatabase (DAO)
Refresh	Requery (DAO)
Refresh (DAO)	Requery (DoCmd)
RefreshLink (DAO)	Requery
RefreshTitleBar	Restore
RegisterDatabase (DAO)	Rollback (DAO)
Remove (VBA)	Run
Rename	RunMacro
Repaint	RunSQL
S–Z

Save	ShowToolbar
Scale	SizeToFit
Seek (DAO)	Synchronize (DAO)
SelectObject	TextWidth
SendObject	TransferDatabase
SetFocus	TransferSpreadsheet
SetMenuItem	TransferText
SetOption	Undo
SetWarnings	Update (DAO)
ShowAllRecords


Application Methods Reference

You can use the following methods with the Application object.

BuildCriteria	OpenCurrentDatabase
CloseCurrentDatabase	RefreshTitleBar
DefaultWorkspaceClone	Run
Echo	SetOption
GetOption	Quit
NewCurrentDatabase


Control Methods Reference

You can use the following methods with controls.

ItemData

Requery

SetFocus


DoCmd Methods Reference

You can use the following methods with the DoCmd object.

ApplyFilter	OpenReport
Beep	OpenTable
CancelEvent	OutputTo
Close	PrintOut
CopyObject	Quit
DeleteObject	Rename
DoMenuItem	RepaintObject
Echo	Requery
FindNext	Restore
FindRecord	RunMacro
GoToControl	RunSQL
GoToPage	Save
GoToRecord	SelectObject
Hourglass	SendObject
Maximize	SetWarnings
Minimize	ShowAllRecords
MoveSize	ShowToolbar
OpenForm	TransferDatabase
OpenModule	TransferSpreadsheet
OpenQuery	TransferText


Form Methods Reference

You can use the following methods with forms.

GoToPage	Repaint
Recalc	Requery
Refresh	SetFocus


Report Methods Reference

You can use the following methods with reports to enhance their appearance.

Circle	Scale
Line	TextHeight
PrintOut	TextWidth
PSet


Properties Reference

The following reference groups all properties by object or collection and lists them alphabetically. An asterisk (*) indicates that the property was added for Microsoft Access 95.

Grouped by Object or Collection

Application	Index, Indexes (DAO)
Collection (VBA)	Parameter, Parameters (DAO)
Container, Containers (DAO)	Property, Properties (DAO)
Control	Query
Database, Databases (DAO)	QueryDef, QueryDefs (DAO)
DBEngine (DAO)	Recordset, Recordsets (DAO)
Debug (VBA)	Relation, Relations (DAO)
DoCmd	Report
Document, Documents (DAO)	Screen
Err (VBA)	TableDef, TableDefs (DAO)
Field, Fields (DAO)	Table
Form	User, Users (DAO)
Group, Groups (DAO)	Workspace, Workspaces (DAO)
Listed Alphabetically

A

AbsolutePosition (DAO)*	AllowFilters
Action	AllowFullMenus*
ActiveControl	AllowShortcutMenus*
ActiveDatasheet*	AllowSpecialKeys*
ActiveForm	AllowToolbarChanges*
ActiveReport	AllowZeroLength
AddColon	AllowZeroLength (DAO)
AfterDelConfirm	AppIcon*
AfterInsert	Application*
AfterUpdate	AppTitle*
Alias	Attributes (DAO)
AllowAdditions*	AutoActivate
AllowAutoCorrect*	AutoCenter
AllowBreakIntoCode*	AutoExpand
AllowBuiltInToolbars*	AutoLabel
AllowBypassKey*	AutoRepeat
AllowDeletions*	AutoResize
AllowEditing	AutoTab
AllowEdits*
B

BackColor	Bookmark (DAO)
BackStyle	Bookmarkable (DAO)
BeforeDelConfirm	BorderColor
BeforeInsert	BorderStyle
BeforeUpdate	BorderWidth
BOF (DAO)	BoundColumn
Bookmark
C

CacheSize (DAO)	ColumnWidths
CacheStart (DAO)	Connect (DAO)
Cancel	Container (DAO)
CanGrow	ControlBox
CanShrink	ControlSource
Caption	ControlTipText*
Class	ControlType*
CloseButton*	Count (DAO)
Clustered (DAO)	Count
CodeContextObject*	Count (VBA)
CollatingOrder (DAO)	CurrentObjectType
Column	CurrentRecord*
ColumnCount	CurrentSectionLeft
ColumnHeadings	CurrentSectionTop
ColumnHeads	CurrentView
ColumnHidden	CurrentX
ColumnOrder	CurrentY
ColumnWidth	Cycle*
D

Database Properties*	DefaultValue
DataEntry*	DefaultValue (DAO)
DatasheetCellsEffect*	DefaultView
DatasheetFontHeight	Description
DatasheetFontItalic	Description (DAO)*
DatasheetFontName	Description (VBA)*
DatasheetFontUnderline	DestConnectStr
DatasheetFontWeight	DestinationDB
DatasheetGridLinesColor*	DestinationTable
DatasheetGridLinesBehavior*	Dirty
DataType	DisplayControl*
DataUpdatable (DAO)	DisplayType
DateCreated (DAO)	DisplayWhen
DateGrouping	DistinctCount (DAO)*
DBEngine*	DividingLines*
DecimalPlaces	DrawMode
Default	DrawStyle
DefaultEditing	DrawWidth
DefaultPassword (DAO)*	Dynaset
DefaultUser (DAO)*
E–F

EditMode (DAO)*	FontSize
Enabled	FontUnderline
EnterKeyBehavior	FontWeight
EOF (DAO)	ForceNewPage
EventProcPrefix	ForeColor
FastLaserPrinting	ForeignName (DAO)
FieldName	ForeignTable (DAO)
FieldSize	Form
FillColor	Format
FillStyle	Format — Date/Time Data Types
Filter (DAO)	Format — Number and Currency Data Types
FilterLookup*	Format — Text and Memo Data Types
FilterOn*	Format — Yes/No Data Types
FontBold	FormatCount
FontItalic	FrozenColumns
FontName
G–H

GridX	Height
GridY	HelpContext (DAO)*
GroupFooter	HelpContextID
GroupHeader	HelpFile
GroupInterval	HelpFile (DAO)*
GroupLevel	HelpFile (VBA)*
GroupOn	HideDuplicates
GrpKeepTogether*	hWnd
HasContinued*	hWndAccessApp*
HasData*
I–K

IgnoreNulls	InsideWidth*
IgnoreNulls (DAO)	ImageHeight*
Index (DAO)	ImageWidth*
Indexed	IsolateODBCTrans (DAO)*
Inherit (DAO)*	Item
Inherited (DAO)	KeepLocal (DAO)*
IniPath (DAO)*	KeepTogether — Groups
InputMask	KeepTogether — Sections
InSelection	KeyPreview*
InsideHeight*
L

LabelAlign	LinkMasterFields
LabelX	ListCount
LabelY	ListIndex
LastModified (DAO)	ListRows
LastUpdated (DAO)	ListWidth
LayoutForPrint	Locked
Left	LockEdits (DAO)
LimitToList	LoginTimeout (DAO)
LineSlant	LogMessages (DAO)
LinkChildFields	lpOLEObject
M–N

Me	Name (DAO)
MenuBar	NavigationButtons
MinMaxButtons*	NewRecord*
Modal	NewRowOrCol
Module	NewValues*
MoveLayout	NoMatch (DAO)
MultiSelect*	Number (DAO)*
Name	Number (VBA)
O

Object	OnFormat
Object Properties*	OnLostFocus
ObjectPalette	OnMouseDown
ObjectVerbs	OnMouseMove
ObjectVerbsCount	OnMouseUp
ODBCConnectStr	OnNoData
ODBCTimeout (DAO)	OnNotInList
ODBCTimeout	OnOpen
OldValue	OnPage
OLEClass	OnPrint
OLEType	OnResize
OLETypeAllowed	OnRetreat
OnActivate	OnTimer
OnChange	OnUnload
OnClick	OnUpdated
OnClose	OpenArgs
OnCurrent	OptionValue
OnDblClick	OrderBy*
OnDeactivate	OrderByOn*
OnDelete	OrdinalPosition
OnEnter	OutputAllFields
OnError	Owner (DAO)
OnExit
P

Page	PicturePages*
PageFooter	PictureSizeMode*
PageHeader	PictureTiling*
Pages	PictureType*
Painting	PID (DAO)
PaintPalette	PopUp
PaletteSource	PreviousControl
Parent	Primary
Password (DAO)*	Primary (DAO)
PercentPosition (DAO)	PrintCount
Permissions (DAO)	PrintSection
Picture	PrtDevMode
PictureAlignment*	PrtDevNames
PictureData*	PrtMip
Q–R

QueryTimeout (DAO)	Report
RecordCount (DAO)	Required
RecordLocks	Required (DAO)
RecordsAffected (DAO)*	Restartable (DAO)
RecordSelectors	ReturnsRecords
RecordsetClone	ReturnsRecords (DAO)
RecordsetType*	RowHeight
RecordSource	RowSource
RepeatSection*	RowSourceType
Replicable (DAO)*	RunningSum
ReplicaID (DAO)*	RunPermissions
S

ScaleHeight	SortOrder
ScaleLeft	Source
ScaleMode	Source (DAO)*
ScaleTop	SourceConnectStr
ScaleWidth	SourceDatabase
ScrollBars	SourceDoc
Section	SourceField (DAO)
Selected*	SourceItem
SelHeight*	SourceObject
SelLeft*	SourceTable (DAO)
SelLength	SourceTableName (DAO)
SelStart	SpecialEffect
SelText	SQL (DAO)
SelTop*	StartupForm*
SelWidth*	StartupMenuBar*
ShortcutMenu	StartupShortcutMenuBar*
ShortcutMenuBar*	StartupShowDBWindow*
ShowGrid	StartupShowStatusBar*
Size (DAO)	StatusBarText
SizeMode	SystemDB (DAO)*
Sort (DAO)
T–U

TabIndex	TripleState*
Table (DAO)	Type (DAO)
TabStop	Unique
Tag	Unique (DAO)
Text	UniqueRecords
TextAlign	UniqueValues
TimerInterval	Updatable (DAO)
Top	UpdateOptions
TopValues	UserControl*
Transactions (DAO)	UserName (DAO)
Transparent
V–Z

V1xNullBehavior	Version (DAO)
V1xNullBehavior (DAO)	ViewsAllowed
ValidateOnSet (DAO)	Visible
ValidationRule	Visible (Application Object)*
ValidationRule (DAO)	WhatsThisButton*
ValidationText	Width
ValidationText (DAO)	WillContinue*
Value	WindowHeight
Value (DAO)	WindowWidth
Verb


Query Properties

Each query has property settings that you can change to alter the way the query behaves and how the query results look.

For more information on a query property, click a property name below. An asterisk (*) indicates that the property applies to query fields or field lists. A property listed with no asterisk applies to queries as a whole.

A–D

Alias*	DatasheetGridLinesBehavior
Caption*	DatasheetGridLinesColor
ColumnHeadings	Description
ColumnHidden*	DestConnectStr
ColumnOrder*	DestinationDB
ColumnWidth*	DestinationTable
DatasheetCellsEffect	DisplayControl*
E–Q

Filter	OrderBy
Format*	OrderByOn
FrozenColumns	OutputAllFields
InputMask*	PrtDevMode
LogMessages	PrtDevNames
ODBCConnectStr	PrtMip
ODBCTimeout
R–Z

RecordLocks	SelWidth
ReturnsRecords	Source*
RowHeight	SourceConnectStr
RunPermissions	SourceDatabase
SelLeft	TopValues
SelHeight	UniqueRecords
SelTop	UniqueValues


Form Properties

Each form has property settings that you can change to alter the way the form looks and behaves.

For more information on a form property, click a property name below. A property listed with no asterisk applies to forms but not to form sections. A single asterisk (*) indicates that the property applies only to form sections; two asterisks (**) indicate that the property applies to both forms and form sections.

A

AfterDelConfirm	AllowFilters
AfterUpdate	Application
AllowAdditions	AutoCenter
AllowDeletions	AutoResize
AllowEdits
B

BackColor*	Bookmark
BeforeDelConfirm	BorderStyle
BeforeUpdate
C

CanGrow*	Count
CanShrink*	CurrentRecord
Caption	CurrentSectionLeft
CloseButton	CurrentSectionTop
ControlBox	Cycle
D

DataEntry	Dirty
DatasheetCellsEffect	DisplayWhen*
DatasheetGridLinesBehavior	DividingLines
DatasheetGridLinesColor	Dynaset
DefaultView
E–H

EventProcPrefix	GridX
FastLaserPrinting	GridY
Filter	Height*
FilterOn	HelpContextID
ForceNewPage*	HelpFile
Form	hWnd
FrozenColumns
I–N

InsideHeight	MinMaxButtons
InsideWidth	Modal
KeepTogether — Sections*	Module
KeyPreview	Name**
LayoutForPrint	NavigationButtons
Me	NewRecord
MenuBar	NewRowOrCol*
O

Object Properties	OnKeyUp
ObjectPalette	OnLoad
OnActivate	OnLostFocus
OnClick**	OnMouseDown**
OnClose	OnMouseMove**
OnCurrent	OnMouseUp**
OnDblClick**	OnOpen
OnDeactivate	OnResize
OnDelete	OnTimer
OnError	OnUnload
OnGotFocus	OpenArgs
OnKeyDown	OrderBy
OnKeyPress	OrderByOn
P–Z

Page	RecordsetClone
Pages	RecordSource
Painting	ScrollBars
PaintPalette	Section
PaletteSource	ShortcutMenu
Parent*	ShortcutMenuBar
PopUp	ShowGrid
PrtDevMode	SpecialEffect*
Picture	Tag**
PictureAlignment	TimerInterval
PictureData	ViewsAllowed
PictureSizeMode	Visible**
PictureTiling	Width
PictureType	WhatsThisButton
RecordLocks	WindowHeight
RecordSelectors	WindowWidth
RecordsetClone


Report Properties

Each report has property settings that you can use to specify how a report looks and behaves.

For more information on a report property, click a property name below. An asterisk (*) indicates that the property applies only to report sections.

A–G

Application	FontBold
BackColor*	FontItalic
CanGrow*	FontName
CanShrink*	FontSize
Caption	FontUnderline
Count	FontWeight
CurrentX	Form
CurrentY	ForceNewPage*
DateGrouping	FormatCount
DrawMode	GridX
DrawStyle	GridY
DrawWidth	GroupFooter
EventProcPrefix*	GroupHeader
FastLaserPrinting	GroupInterval
FillColor	GroupLevel
FillStyle	GroupOn
Filter	GrpKeepTogether
FilterOn
H–O

HasContinued	NextRecord*
HasData	Object Properties
Height*	ObjectPalette
HelpContextID	OnActivate
HelpFile	OnClose
hWnd	OnDeactivate
KeepTogether — Groups	OnError
KeepTogether — Sections*	OnFormat*
LayoutForPrint	OnNoData
Me	OnOpen
MenuBar	OnPage*
Module	OnPrint*
MoveLayout*	OnRetreat*
Name**	OrderBy
NewRowOrCol*	OrderByOn
P–Q

Page	PictureData
PageFooter	PicturePages
PageHeader	PictureSizeMode
Pages	PictureTiling
Painting	PictureType
PaintPalette	PrintCount
PaletteSource	PrintSection*
Parent*	PrtDevMode
Picture	PrtDevNames
PictureAlignment	PrtMip
R–S

RecordLocks	ScaleTop
RecordSource	ScaleWidth
RepeatSection	Section
Report	SelHeight
RunningSum	SelTop
ScaleHeight	ShortcutMenuBar
ScaleLeft	SortOrder
ScaleMode
T–Z

Tag**	Width
Top	WillContinue
Visible**


Field Properties

Each field has property settings that you can change to alter the way the field looks and behaves. The properties available for a field are dependent on the field data type.

For more information on a field property, click a property name below.

AllowZeroLength	IgnoreNulls
BorderColor	Indexed
BorderStyle	InputMask
BorderWidth	LimitToList
BoundColumn	ListRows
Caption	ListWidth
ColumnCount	NewValues
ColumnHeads	Primary
ColumnWidths	PrtDevModes
DatasheetCellsEffect	PrtDevNames
DatasheetGridLinesBehavior	PrtMip
DataType	Required
DecimalPlaces	RowSource
DefaultValue	RowSourceType
Description	SelHeight
DisplayControl	SelTop
FieldName	SortOrder
FieldSize	SpecialEffect
ForeColor	Unique
Format	ValidationRule
FrozenColumns	ValidationText


Table Properties

Each table has property settings that you can change to alter the way the table looks and behaves.

For more information on a table property, click a property name below.

Description	ValidationRule
Filter	ValidationText
OrderBy


Control Properties

Each control has property settings that you can change to alter the way the control looks and behaves.

You can change the default property settings before you add a control to a form or report, or you can change property settings for a control that has already been placed on a form or report. To see which way is available for a particular property, see the topic for that property.

For more information on a control property, click a control name below.

Bound Object Frame	Option Button
Check Box	Option Group
Combo Box	Page Break
Command Button	Rectangle
Chart	Subform/Subreport
Image	Text Box
Label	Toggle Button
Line	Unbound Object Frame
List Box


Bound Object Frame Control Properties

The following list identifies the properties you can set for a bound object frame control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Action	ObjectVerbsCount
AddColon	OldValue (FO)
AfterUpdate (FO)	OLEType
Application	OLETypeAllowed
AutoActivate (FO)	OnClick (FO)
AutoLabel	OnDblClick (FO)
BackColor	OnEnter (FO)
BackStyle	OnExit (FO)
BeforeUpdate (FO)	OnGotFocus (FO)
BorderColor	OnKeyDown (FO)
BorderStyle	OnKeyPress (FO)
BorderWidth	OnKeyUp (FO)
Class	OnLostFocus (FO)
ControlSource	OnMouseDown (FO)
ControlTipText	OnMouseMove (FO)
ControlType	OnMouseUp (FO)
DisplayType	OnUpdated (FO)
DisplayWhen (FO)	Parent
Enabled (FO)	Section
EventProcPrefix	ShortcutMenuBar
Height	SizeMode
HelpContextID (FO)	SourceDoc
InSelection (FO)	SourceItem
LabelAlign	SpecialEffect
LabelX	StatusBarText (FO)
LabelY	TabIndex (FO)
Left	TabStop (FO)
Locked (FO)	Tag
lpOLEObject	Top
Name	UpdateOptions
Object	Verb
ObjectPalette	Visible
ObjectVerbs	Width


Check Box Control Properties

The following list identifies the properties you can set for a check box control. Those properties that apply only when the control is on a form or only when it's on a report are followed by (FO) for "Forms Only" or (RO) for "Reports Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	OnDblClick (FO)
AfterUpdate (FO)	OnEnter (FO)
Application	OnExit (FO)
AutoLabel	OnGotFocus (FO)
BeforeUpdate (FO)	OnKeyDown (FO)
BorderColor	OnKeyPress (FO)
BorderStyle	OnKeyUp (FO)
BorderWidth	OnLostFocus (FO)
ControlSource	OnMouseDown (FO)
ControlTipText	OnMouseMove (FO)
ControlType	OnMouseUp (FO)
DefaultValue (FO)	OptionValue
DisplayWhen (FO)	Parent
Enabled (FO)	Section
EventProcPrefix	ShortcutMenuBar
Height	SpecialEffect
HelpContextID (FO)	StatusBarText (FO)
HideDuplicates (RO)	TabIndex (FO)
InSelection (FO)	TabStop (FO)
LabelAlign	Tag
LabelX	Top
LabelY	TripleState
Left	ValidationRule (FO)
Locked (FO)	ValidationText (FO)
Name	Value
OldValue (FO)	Visible
OnClick (FO)	Width


Combo Box Control Properties

The following list identifies the properties you can set for a combo box control. Those properties that apply only when the control is on a form or only when it's on a report are followed by (FO) for "Forms Only" or (RO) for "Reports Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	LimitToList
AfterUpdate (FO)	ListCount (FO)
AllowAdditions	ListIndex (FO)
AllowAutoCorrect	ListRows
Application	ListWidth
AutoExpand	Locked (FO)
AutoRepeat (FO)	Name
AutoLabel	OldValue (FO)
BackColor	OnChange (FO)
BackStyle	OnClick (FO)
BeforeUpdate (FO)	OnDblClick (FO)
BorderColor	OnEnter (FO)
BorderStyle	OnExit (FO)
BorderWidth	OnGotFocus (FO)
BoundColumn	OnKeyDown (FO)
Column	OnKeyPress (FO)
ColumnCount	OnKeyUp (FO)
ColumnHeads	OnLostFocus (FO)
ColumnWidths	OnMouseDown (FO)
ControlTipText (FO)	OnMouseMove (FO)
ControlType	OnMouseUp (FO)
ControlSource	OnNotInList (FO)
DecimalPlaces	Parent
DefaultValue (FO)	RowSource
DisplayWhen (FO)	RowSourceType
Enabled (FO)	Section
EventProcPrefix	SelLength (FO)
FontBold	SelStart (FO)
FontItalic	SelText (FO)
FontName	ShortcutMenuBar
FontSize	SpecialEffect
FontUnderline	StatusBarText (FO)
FontWeight	TabIndex (FO)
ForeColor	TabStop (FO)
Format	Tag
Height	Text
HelpContextID (FO)	TextAlign
HideDuplicates (RO)	Top
InputMask	ValidationRule (FO)
InSelection (FO)	ValidationText (FO)
LabelAlign	Value
LabelX	Visible
LabelY	Width
Left


Command Button Control Properties

The following list identifies the properties you can set for a command button control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	OnClick (FO)
Application	OnDblClick (FO)
AutoLabel	OnEnter (FO)
AutoRepeat (FO)	OnExit (FO)
Cancel (FO)	OnGotFocus (FO)
Caption	OnKeyDown (FO)
ControlTipText (FO)	OnKeyPress (FO)
ControlType	OnKeyUp (FO)
Default	OnLostFocus (FO)
DisplayWhen (FO)	OnMouseDown (FO)
Enabled (FO)	OnMouseMove (FO)
EventProcPrefix	OnMouseUp (FO)
FontBold	Parent
FontItalic	Picture
FontName	PictureType
FontSize	Section
FontUnderline	ShortcutMenuBar
Height	StatusBarText (FO)
HelpContextID (FO)	TabIndex (FO)
InSelection (FO)	TabStop (FO)
LabelAlign	Tag
LabelX	Top
LabelY	Transparent
Left	Visible
Name	Width
ObjectPalette


Graph Control Properties
Chart Control Properties

The following list identifies the properties you can set for a chart control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Action	ObjectVerbs
AutoActivate (FO)	ObjectVerbsCount
BackColor	OLEClass
BackStyle	OLEType
BorderColor	OLETypeAllowed
BorderStyle	OnClick (FO)
BorderWidth	OnDblClick (FO)
Class	OnMouseDown (FO)
ColumnCount	OnMouseMove (FO)
ColumnHeads	OnMouseUp (FO)
ControlTipText (FO)	Parent
ControlType	RowSource
DisplayType	RowSourceType
DisplayWhen (FO)	Section
Enabled (FO)	ShortcutMenuBar
EventProcPrefix	SizeMode
Height	SourceDoc
HelpContextID (FO)	SourceItem
InSelection (FO)	SourceObject
Item	SpecialEffect
Left	TabIndex (FO)
LinkChildFields	TabStop (FO)
LinkMasterFields	Tag
Locked (FO)	Top
lpOLEObject	UpdateOptions
Name	Verb
Object	Visible
ObjectPalette	Width


Image Control Properties

The following list identifies the properties you can set for an image control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Application	OnMouseDown (FO)
BackColor	OnMouseMove (FO)
BackStyle	OnMouseUp (FO)
BorderColor	Parent
BorderStyle	Picture
BorderWidth	PictureAlignment
ControlTipText (FO)	PictureData
ControlType	PictureTiling (FO)
DisplayWhen (FO)	PictureType
EventProcPrefix	Section
Height	ShortcutMenuBar
HelpContextID	SizeMode
ImageHeight	SpecialEffect
ImageWidth	Tag
Left	Top
Name	Visible
OnClick (FO)	Width
OnDblClick (FO)


Label Control Properties

The following list identifies the properties you can set for a label control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Application	HelpContextID
BackColor	InSelection (FO)
BackStyle	Left
BorderColor	Name
BorderStyle	OnClick (FO)
BorderWidth	OnDblClick (FO)
Caption	OnMouseDown (FO)
ControlTipText (FO)	OnMouseMove (FO)
ControlType	OnMouseUp (FO)
DisplayWhen (FO)	Parent
EventProcPrefix	Section
FontBold	ShortcutMenuBar
FontItalic	SpecialEffect
FontName	Tag
FontSize	TextAlign
FontUnderline	Top
FontWeight	Visible
ForeColor	Width
Height


Line Control Properties

The following list identifies the properties you can set for a line control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Application	LineSlant
BorderColor	Name
BorderStyle	Parent
BorderWidth	Section
DisplayWhen (FO)	SpecialEffect
EventProcPrefix	Tag
Height	Top
InSelection (FO)	Visible
Left	Width


List Box Control Properties

The following list identifies the properties you can set for a list box control. Those properties that apply only when the control is on a form or only when it's on a report are followed by (FO) for "Forms Only" or (RO) for "Reports Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	ListCount (FO)
AfterUpdate (FO)	ListIndex (FO)
Application	Locked (FO)
AutoLabel	MultiSelect
BackColor	Name
BeforeUpdate (FO)	OldValue (FO)
BorderColor	OnClick (FO)
BorderStyle	OnDblClick (FO)
BorderWidth	OnEnter (FO)
BoundColumn	OnExit (FO)
Column (FO)	OnGotFocus (FO)
ColumnCount	OnKeyDown (FO)
ColumnHeads	OnKeyPress (FO)
ColumnWidths	OnKeyUp (FO)
ControlTipText (FO)	OnLostFocus (FO)
ControlType	OnMouseDown (FO)
ControlSource	OnMouseMove (FO)
DefaultValue (FO)	OnMouseUp (FO)
DisplayWhen (FO)	Parent
Enabled (FO)	RowSource
EventProcPrefix	RowSourceType
FontBold	Section
FontItalic	Selected
FontName	ShortcutMenuBar
FontSize	SpecialEffect
FontUnderline	StatusBarText (FO)
FontWeight	TabIndex (FO)
ForeColor	TabStop (FO)
Height	Tag
HelpContextID (FO)	Top
HideDuplicates (RO)	ValidationRule (FO)
InSelection (FO)	ValidationText (FO)
LabelAlign	Value
LabelX	Visible
LabelY	Width
Left


Option Button Control Properties

The following list identifies the properties you can set for an option button control. Those properties that apply only when the control is on a form or only when it's on a report are followed by (FO) for "Forms Only" or (RO) for "Reports Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	OnDblClick (FO)
AfterUpdate (FO)	OnEnter (FO)
Application	OnExit (FO)
AutoLabel	OnGotFocus (FO)
BeforeUpdate (FO)	OnKeyDown (FO)
BorderColor	OnKeyPress (FO)
BorderStyle	OnKeyUp (FO)
BorderWidth	OnLostFocus (FO)
ControlSource	OnMouseDown (FO)
ControlTipText (FO)	OnMouseMove (FO)
ControlType	OnMouseUp (FO)
DefaultValue (FO)	OptionValue
DisplayWhen (FO)	Parent
Enabled (FO)	Section
EventProcPrefix	ShortcutMenuBar
Height	SpecialEffect
HelpContextID (FO)	StatusBarText (FO)
HideDuplicates (RO)	TabIndex (FO)
InSelection (FO)	TabStop (FO)
LabelAlign	Tag
LabelX	Top
LabelY	TripleState
Left	ValidationRule (FO)
Locked (FO)	ValidationText (FO)
Name	Value
OldValue (FO)	Visible
OnClick (FO)	Width


Option Group Control Properties

The following list identifies the properties you can set for an option group control. Those properties that apply only when the control is on a form or only when it's on a report are followed by (FO) for "Forms Only" or (RO) for "Reports Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	Locked (FO)
AfterUpdate (FO)	Name
Application	OldValue (FO)
AutoLabel	OnClick (FO)
BackColor	OnDblClick (FO)
BackStyle	OnEnter (FO)
BeforeUpdate (FO)	OnExit (FO)
BorderColor	OnMouseDown (FO)
BorderStyle	OnMouseMove (FO)
BorderWidth	OnMouseUp (FO)
ControlSource	Parent
ControlTipText (FO)	Section
DefaultValue (FO)	ShortcutMenuBar
DisplayWhen (FO)	SpecialEffect
Enabled (FO)	StatusBarText (FO)
EventProcPrefix	TabIndex (FO)
Height	TabStop (FO)
HelpContextID (FO)	Tag
HideDuplicates (RO)	Top
InSelection	ValidationRule (FO)
LabelAlign	ValidationText (FO)
LabelX	Value
LabelY	Visible
Left	Width


Page Break Control Properties

The following list identifies the properties you can set for a page break control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Application	Parent
ControlType	Section
EventProcPrefix	Tag
InSelection (FO)	Top
Left	Visible
Name


Rectangle Control Properties

The following list identifies the properties you can set for a rectangle control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Application	OnClick (FO)
BackColor	OnDblClick (FO)
BackStyle	OnMouseDown (FO)
BorderColor	OnMouseMove (FO)
BorderStyle	OnMouseUp (FO)
BorderWidth	Parent
DisplayWhen (FO)	Section
EventProcPrefix	SpecialEffect
Height	Tag
HelpContextID	Top
InSelection (FO)	Visible
Left	Width
Name


Subform/Subreport Control Properties

The following list identifies the properties you can set for a subform/subreport control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	LinkChildFields
Application	LinkMasterFields
AutoLabel	Locked (FO)
BorderColor	Name
BorderStyle	OnClick (FO)
BorderWidth	OnDblClick (FO)
CanGrow	OnEnter (FO)
CanShrink	OnExit (FO)
ControlType	Parent
DisplayWhen (FO)	Report
Enabled (FO)	Section
EventProcPrefix	SourceObject
Form	SpecialEffect
Height	StatusBarText (FO)
HelpContextID	TabIndex (FO)
InSelection (FO)	TabStop (FO)
LabelAlign	Tag
LabelX	Top
LabelY	Visible
Left	Width


Text Box Control Properties

The following list identifies the properties you can set for a text box control. Those properties that apply only when the control is on a form or only when it's on a report are followed by (FO) for "Forms Only" or (RO) for "Reports Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	Left
AfterUpdate (FO)	Locked (FO)
AllowAutoCorrect	Name
Application	OldValue (FO)
AutoLabel	OnChange (FO)
AutoTab (FO)	OnClick (FO)
BackColor	OnDblClick (FO)
BackStyle	OnEnter (FO)
BeforeUpdate (FO)	OnExit (FO)
BorderColor	OnGotFocus (FO)
BorderStyle	OnKeyDown (FO)
BorderWidth	OnKeyPress (FO)
CanGrow	OnLostFocus (FO)
CanShrink	OnMouseDown (FO)
ControlSource	OnKeyUp (FO)
ControlTipText (FO)	OnMouseMove (FO)
DecimalPlaces	OnMouseUp (FO)
DefaultValue (FO)	OldValue
DisplayWhen (FO)	Parent
Enabled (FO)	RunningSum (RO)
EnterKeyBehavior (FO)	ScrollBars (FO)
EventProcPrefix	Section
FilterLookup	SelLength (FO)
FontBold	SelStart (FO)
FontItalic	SelText (FO)
FontName	ShortcutMenuBar
FontSize	SpecialEffect
FontUnderline	StatusBarText (FO)
FontWeight	TabIndex (FO)
ForeColor	TabStop (FO)
Format	Tag
Height	Text
HelpContextID (FO)	TextAlign
HideDuplicates (RO)	Top
InputMask	ValidationRule (FO)
InSelection (FO)	ValidationText (FO)
LabelAlign	Value
LabelX	Visible
LabelY	Width


Toggle Button Control Properties

The following list identifies the properties you can set for a toggle button control. Those properties that apply only when the control is on a form or only when it's on a report are followed by (FO) for "Forms Only" or (RO) for "Reports Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

AddColon	OldValue (FO)
AfterUpdate (FO)	OnClick (FO)
Application	OnDblClick (FO)
AutoLabel	OnEnter (FO)
BeforeUpdate (FO)	OnExit (FO)
Caption	OnGotFocus (FO)
ControlSource	OnKeyDown (FO)
ControlTipText (FO)	OnKeyPress (FO)
ControlType	OnKeyUp (FO)
DefaultValue (FO)	OnLostFocus (FO)
DisplayWhen (FO)	OnMouseDown (FO)
Enabled (FO)	OnMouseMove (FO)
EventProcPrefix	OnMouseUp (FO)
FontBold	OptionValue
FontItalic	Parent
FontName	Picture
FontSize	PictureData
FontUnderline	PictureType
FontWeight	Section
ForeColor	ShortcutMenuBar
Height	StatusBarText (FO)
HelpContextID (FO)	TabIndex (FO)
HideDuplicates (RO)	TabStop (FO)
InSelection (FO)	Tag
LabelAlign	Top
LabelX	TripleState
LabelY	ValidationRule (FO)
Left	ValidationText (FO)
Locked (FO)	Value
Name	Visible
ObjectPalette	Width


Unbound Object Frame Control Properties

The following list identifies the properties you can set for an unbound object frame control. Those properties that apply only when the control is on a form are followed by (FO) for "Forms Only."

Click any name below to display additional information about that property, such as other restrictions concerning when the property is available, and whether you can set it using the property sheet, a macro, or Visual Basic.

Action	OLEClass
Application	OLEType
AutoActivate (FO)	OLETypeAllowed
BackColor	OnClick (FO)
BackStyle	OnDblClick (FO)
BorderColor	OnEnter (FO)
BorderStyle	OnExit (FO)
BorderWidth	OnGotFocus (FO)
Class	OnLostFocus (FO)
ColumnCount	OnMouseDown (FO)
ColumnHeads	OnMouseMove (FO)
ControlTipText (FO)	OnMouseUp (FO)
ControlType	OnUpdated (FO)
DisplayType	Parent
DisplayWhen (FO)	RowSource
Enabled (FO)	RowSourceType
EventProcPrefix	Section
Height	ShortcutMenuBar
HelpContextID (FO)	SizeMode
InSelection (FO)	SourceDoc
Item	SourceItem
Left	SourceObject
LinkChildFields	SpecialEffect
LinkMasterFields	TabIndex (FO)
Locked (FO)	TabStop (FO)
lpOLEObject	Tag
Name	Top
Object	UpdateOptions
ObjectPalette	Verb
ObjectVerbs	Visible
ObjectVerbsCount	Width


Changed Property Names

The following table shows the properties that have new names in Microsoft Access 95 (version 7.0). In addition, Microsoft Access 95 includes many new properties, which are indicated with an asterisk (*) in the Properties Reference.

Version 2.0 property name	Version 7.0 property name
AllowEdits, DefaultEditing	AllowAdditions, AllowDeletions, AllowEdits, DataEntry
MaxButton, MinButton	MinMaxButtons
BorderLineStyle	BorderStyle
AllowUpdating	RecordsetType
ShowGrid	DatasheetGridLinesBehavior


Setting Properties Using Macros

From a macro, you can set properties for Form, Report, and Control objects, as well as form and report sections. Use the SetValue action from a macro to set the value of a property.

You can't use a macro to set properties of other Microsoft Access objects or data access objects, or to set the default properties of a control, but you can set them either from Visual Basic or in the Microsoft Access window.

To set a form, report, or control property using a macro

1	In a macro, add a SetValue action.

2	Set the Item action argument of the SetValue action to an expression that refers to the property you want to set:

To set a form or report property, use the syntax Forms!formname.propertyname or Reports!reportname.propertyname. For example, the following expression refers to the Visible property of the Customers form.

Forms![Customers].Visible

To set a property of a control on a form or report, use the syntax Forms!formname!controlname.propertyname or Reports!reportname!controlname.propertyname. For example, the following expression refers to the Visible property of the HiddenPageBreak control on the Invoices report.

Reports![Invoices]![HiddenPageBreak].Visible

Tip   If the macro containing the SetValue action runs from the form or report with the property you want to set, you can refer to the property using just the syntax propertyname. However, it's a good idea to use the full syntax to refer to the property to avoid conflicts with names of controls or Visual Basic keywords. For example, Name is a Microsoft Access property; if you also have a control on your form called Name, you should use the full syntax to refer to both the control and the property.

3	Set the Expression action argument of the SetValue action to the value you want to set the property to. If the setting is a string, be sure to enclose it in double quotation marks ("). For example, to set the Caption property of a form to Orders, you would enter "Orders" in the Expression argument.

To set a section property using a macro

1	In a macro, add a SetValue action.

2	In the Item action argument, use the syntax Forms!formname.Section(n).propertyname to refer to the property you want to set. The integer n refers to a particular section on the form or report, as described in the Section property. For example, the following expression refers to the Visible property of the page header section of the Customers form.

Forms!Customers.Section(3).Visible

3	Set the Expression action argument as described above.

Notes

Search the online index for the individual property you wish to set for information on:

Whether or not you can set the property from a macro.

Views in which you can set the property. Not all properties can be set in all views. For example, you can set a form's BorderStyle property only in form Design view.

Which values you should use to set the property. You may need to set the property using the settings you would use in Visual Basic rather than those you would use in the property sheet. For example, if the property settings are selections from a drop-down list, you must use the value or numeric equivalent for each selection.


Setting Properties Using Visual Basic

You can set most properties from Visual Basic code. How you set a property depends on whether you are setting it for a Form, Report, or Control object, or for a data access object. The following topics outline the steps involved for setting properties of each type of object.

Setting Form, Report, and Control Properties in Visual Basic

Setting Properties of Data Access Objects in Visual Basic


 Setting Form, Report, and Control Properties in Visual Basic

Form, Report, and Control objects are Microsoft Access objects. You can set properties for these objects from within a Sub, Function , or event procedure. You can also set properties for form and report sections.

To set a property of a form or report

Refer to the individual form or report within the Forms or Reports collection, followed by the name of the property and its value. For example, to set the Visible property of the Customers form to True (-1), use the following line of code.

Forms!Customers.Visible = True

To set a property of a control

Refer to the control in the Controls collection of the Form or Report object on which it resides. You can refer to the Controls collection either implicitly or explicitly, but it's faster to refer to it implicitly. The following examples set the Visible property of a text box called CustomerID on the Customers form.

Forms!Customers!CustomerID.Visible = True	' Faster method.

Forms!Customers.Controls!CustomerID.Visible = True	' Slower method.

To set a property of a form or report section

Refer to the form or report within the Forms or Reports collection, followed by the Section property and the index number that identifies the section. The following example sets the Visible property of the page header section of the Customers form to False (0).

Forms!Customers.Section(3).Visible = False

Notes

Search the online index for the individual property you wish to set for information on:

Whether or not you can set the property from Visual Basic.

Views in which you can set the property. Not all properties can be set in all views. For example, you can set a form's BorderStyle property only in form Design view.

Which values you should use to set the property. You often use different settings when you set a property in Visual Basic instead of in the property sheet. For example, if the property settings are selections from a drop-down list, you must use the value or numeric equivalent for each selection.

To set default properties for controls from Visual Basic, use the DefaultControl method.


Setting Properties of Data Access Objects in Visual Basic

Data access objects enable you to manipulate the structure of your database and the data it contains from Visual Basic. Many data access objects correspond to objects that you see in your database [image] for example, a TableDef object corresponds to a Microsoft Access table. A Field object corresponds to a field in a table.

Most of the properties you can set on data access objects are data access properties. These properties are defined by the Microsoft Jet database engine, and are set the same way in any application that includes the Jet database engine. Some properties you can set on data access objects are defined by Microsoft Access, and aren't automatically recognized by the Jet database engine. You set properties on data access objects differently depending whether a property is defined by the Jet database engine or by Microsoft Access.

Setting Data Access Properties on Data Access Objects

To set a property that is defined by the Jet database engine, refer to the object in the data access object hierarchy. The easiest and fastest way to do this is to create object variables that represent the different objects you need to work with, and refer to the object variables in subsequent steps in your code. For example, the following code creates a new TableDef object and sets its Name property.

Dim dbs As Database, tdf As TableDef

Set dbs = CurrentDb

Set tdf = dbs.CreateTableDef

tdf.Name = "Contacts"

Setting Microsoft Access Properties on Data Access Objects

When you set a property that is defined by Microsoft Access, but applies to a data access object, the Jet database engine doesn't automatically recognize the property as a valid property. The first time you set the property, you must create the property and append it to the Properties collection of the object to which it applies. Once the property is in the Properties collection, it can be set in the same manner as any data access property.

If the property is set for the first time in the user interface, it is automatically added to the Properties collection, and you can set it normally.

When writing procedures to set properties defined by Microsoft Access, you should include error-handling code to verify that the property you are setting already exists in the Properties collection. See the Help topic on the CreateProperty method or the individual property topic for more information.

Keep in mind that when you create the property, you must correctly specify its Type property before you append it to the Properties collection. You can determine the Type property based on the information in the Settings section of the Help topic for the individual property. The following table provides some guidelines for determining the setting of the Type property.

If the property setting is	Then the Type property setting should be
A string	dbText
True/False	dbBoolean
An integer	dbInteger
The following table lists some Microsoft Access-defined properties that apply to data access objects.

Object	Microsoft Access-defined properties
Database	AppTitle, AppIcon, StartupShowDBWindow, StartupShowStatusBar, AllowShortcutMenus, AllowFullMenus, AllowBuiltInToolbars, AllowToolbarChanges, AllowBreakIntoCode, AllowSpecialKeys, Replicable, ReplicationConflictFunction
SummaryInfo Container	Title, Subject, Author, Manager, Company, Category, Keywords, Comments (See the Summary tab of the Database Properties dialog box, available by clicking Database Properties on the File menu.)
UserDefined Container	(See the Summary tab of the Database Properties dialog box, available by clicking Database Properties on the File menu.)
TableDef	DatasheetFontHeight, DatasheetFontItalic, DatasheetFontName, DatasheetFontUnderline, DatasheetFontWeight, Description, FrozenColumns, RowHeight, ShowGrid, KeepLocal
QueryDef	DatasheetFontItalic, FrozenColumns, DatasheetFontHeight, LogMessages, DatasheetFontName, RecordLocks, DatasheetFontUnderline, RowHeight, DatasheetFontWeight, ShowGrid, Description, KeepLocal
Field	Caption, DecimalPlaces, ColumnHidden, Description, ColumnOrder, Format, ColumnWidth, InputMask


Setting Form, Report, and Control Properties

Each form, report, form or report section, and control has property settings that you can change to alter the look or behavior of that particular item. You view and change properties in the property sheet.

To set properties

1	In form Design view or report Design view, select the control, section, form, or report for which you want to set the property. You can select:

One or more controls. To select multiple controls, you can click on controls with the SHIFT key pressed, or you can click and drag over the controls you wish to select.

One section. Click on the section you wish to select.

The entire form or report. Click on the form or report selector box in the upper-left corner of the form or report.

2	Display the property sheet by clicking the right mouse button on the object or section, or by clicking the Properties button on the toolbar.

3	Click the property for which you want to set the value, and then do one of the following:

In the property box, type the appropriate setting or expression.

If the property box is a drop-down list, choose a value from the list.

If a Build button appears next to the property box, click it to display a builder or to display a dialog box giving you a choice of builders. For example, you can use the Code Builder, Macro Builder, Query Builder, or Menu Builder to set some properties.

Notes

Microsoft Access provides a Zoom box for typing and viewing expressions or other long property settings. To display the Zoom box, click a property box in the property sheet. Then press SHIFT+F2, or click the right mouse button and then choose Zoom from the menu.

If you select multiple controls but don't see the properties you expect in the property sheet, you may have selected a control that doesn't belong in the group. To remove a control from a group, hold down the SHIFT key and click the control.

You can set the ControlSource property for some controls by typing the property setting in the control itself. For more information, see Create a calculated control.

If the property sheet is displayed and you click a control that's already selected, the property sheet will go blank. If you're entering a property setting in a control, press ENTER to set the value and redisplay the property sheet. If you're not entering a setting, press the ESC key to redisplay the property sheet.

You can change the default property settings so controls you create will have the new default settings.

The property settings of a bound control might not match the corresponding settings in the field in the underlying table or query to which the control is bound. If the settings are different, the form or report settings typically override those in the table or query.

A bound control on a form or report can inherit some properties from the field in the underlying table or query.

When you select multiple controls, only the properties common to the selected controls appear in the property sheet. If the value of a property is the same for all selected controls, that value appears in the property sheet; otherwise, the box for that property is blank. When you change a property, that change affects all selected controls.


Setting Startup Properties and Options in Code

Startup properties affect how your database application appears when it is opened. For example, startup properties enable you to customize the application title bar, menus, toolbars, and startup form. To view the Startup properties dialog box, click Startup on the Tools.

You can set options in the Options dialog box to change various aspects of the application environment while you're working in it. For example, you can set form, report, table, and query default options. To view the Options dialog box, click Options on the Tools menu.

The following topics provide specific information on setting startup properties and options in code.

Setting Startup Properties from Visual Basic

Setting Options from Visual Basic


Setting Startup Properties from Visual Basic

Startup properties are properties of a Database object. A Database object is a data access object supplied by the Microsoft Jet database engine, but startup properties are defined by Microsoft Access, so they aren't automatically recognized by the Jet database engine. If a startup property hasn't been set previously, you must create it and add it to the Properties collection of the Database object. When you set startup properties from Visual Basic, you should include error-handling code to verify that the property exists in the Properties collection. For more information on setting properties defined by Microsoft Access, see Setting Properties of Data Access Objects in Visual Basic.

The names of the startup properties are different from the text that appears in the Startup properties dialog box, available by clicking Startup on the Tools menu. The following table provides the name of each startup property as it is used in Visual Basic code.

Text in Startup dialog box	Property name
Application Title	AppTitle
Application Icon	AppIcon
Display Form	StartupForm
Display Database Window	StartupShowDBWindow
Display Status Bar	StartupShowStatusBar
Menu Bar	StartupMenuBar
Shortcut Menu Bar	StartupShortcutMenuBar
Allow Full Menus	AllowFullMenus
Allow Default Shortcut Menus	AllowShortcutMenus
Allow Built-in Toolbars	AllowBuiltInToolbars
Allow Toolbar Changes	AllowToolbarChanges
Allow Viewing Code After Error	AllowBreakIntoCode
Use Access Special Keys	AllowSpecialKeys


Setting Options from Visual Basic

You use the SetOption and GetOption methods to set and return option values in the Options dialog box from code. To view the Options dialog box, click Options on the Tools menu.

The following tables list the names of all options that can be set or returned from code and the tabs on which they can be found in the Options dialog box, followed by the corresponding string argument that you must pass to the SetOption or GetOption method.

Note   You can't set options on the Module tab of the Options dialog box from Visual Basic; these can be set only from the Options dialog box. The only exception is the Break On All Errors option, which can be set from code. The string argument associated with this option is "Break on All Errors". If you are developing a database application, add-in, library database, or referenced database, make sure that this option is set to False (0) when you have finished debugging your code.

View Tab

Option text	String argument
Status Bar	Show Status Bar
Startup Dialog Box	Show Startup Dialog Box
Hidden Objects	Show Hidden Objects
System Objects	Show System Objects
Names Column	Show Macro Names Column
Conditions Column	Show Conditions Column
Large Toolbar Buttons	Large Toolbar Buttons
Color Buttons on Toolbars	Color Buttons on Toolbars
Show ToolTips	Show ToolTips
General Tab

Option text	String argument
Left Margin	Left Margin
Right Margin	Right Margin
Top Margin	Top Margin
Bottom Margin	Bottom Margin
Default Database Folder	Default Database Directory
New Database Sort Order	New Database Sort Order
Edit/Find Tab

Option text	String argument
Default Find/Replace Behavior	Default Find/Replace Behavior
Record Changes	Confirm Record Changes
Document Deletions	Confirm Document Deletions
Action Queries	Confirm Action Queries
Local Indexed Fields	Show Values in Indexed
Local Non-indexed Fields	Show Values in Non-indexed
ODBC Fields	Show Values in Remote
Don't display lists where more than this number of records read	Show Values Limit
Datasheet Tab

Option text	String argument
Default Colors: Font	Default Font Color
Default Colors: Background	Default Background Color
Default Colors: Gridlines	Default Gridlines Color
Default Font: Font	Default Font Name
Default Font: Weight	Default Font Weight
Default Font: Size	Default Font Size
Default Font: Italic	Default Font Italic
Default Font: Underline	Default Font Underline
Horizontal	Default Gridlines Horizontal
Vertical	Default Gridlines Vertical
Default Column Width	Default Column Width
Default Cell Effect	Default Cell Effect
Show Animations	Show Animations
Tables/Queries Tab

Option text	String argument
Default Field Sizes: Text	Default Text Field Size
Default Field Sizes: Number	Default Number Field Size
Default Field Type	Default Field Type
Autoindex on Import/Create	Autoindex on Import/Create
Show Table Names	Show Table Names
Output All Fields	Output All Fields
Enable AutoJoin	Enable AutoJoin
Run Permissions	Run Permissions
Forms/Reports Tab

Option text	String argument
Selection Behavior	Selection Behavior
Form Template	Form Template
Report Template	Report Template
Keyboard Tab

Option text	String argument
Move After Enter	Move After Enter
Arrow Key Behavior	Arrow Key Behavior
Behavior Entering Field	Behavior Entering Field
Cursor Stops at First/Last Field	Cursor Stops at First/Last Field
Advanced Tab

Option text	String argument
Default Record Locking	Default Record Locking
Default Open Mode	Default Open Mode for Databases
Ignore DDE Requests	Ignore DDE Requests
Enable DDE Refresh	Enable DDE Refresh
OLE/DDE Timeout (sec)	OLE/DDE Timeout (sec)
Number of Update Retries	Number of Update Retries
ODBC Refresh Interval (sec)	ODBC Refresh Interval (sec)
Refresh Interval (sec)	Refresh Interval (sec)
Update Retry Interval (msec)	Update Retry Interval (msec)
The value that you pass to the SetOption method as the setting argument depends on which type of option you are setting. The following table establishes some guidelines for setting options.

If the option is	Then the setting argument is
A text box	A string
A check box	A Boolean value [image] Yes or No, or True or False
An option button in an option group or a drop-down list	An integer corresponding to the options position in the option group or list


Building SQL Statements That Include Variables and Controls

When working with data access objects, you may need to construct an SQL statement in code. For example, if you're creating a new QueryDef object, you must set its SQL property to a valid SQL string. You're also likely to need a SQL statement when creating a Recordset object.

The easiest way to construct a SQL statement is to create a query in the query design grid, switch to SQL view, and copy and paste the corresponding SQL statement into your code.

Often a query must be based on values that the user supplies, or that change in different situations. If this is the case, you'll need to include variables or control values in your query. The Microsoft Jet database engine processes all SQL statements, but not variables or controls. Therefore, you must construct your SQL statement so that Microsoft Access first determines these values and then concatenates them into the SQL statement that is passed to the Jet database engine.

The following example shows how to create a QueryDef object with a simple SQL statement. This query returns all orders from an Orders table that were placed after 3-31-95.

Dim dbs As Database, qdf As QueryDef, strSQL As String

Set dbs = CurrentDb

strSQL = "SELECT * FROM Orders WHERE OrderDate >=#3-31-95#;"

Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)

The next example creates the same QueryDef object using a value stored in a variable. Note that the number signs (#) that denote the date values must be included in the string so that they are concatenated with the date value.

Dim dbs As Database, qdf As QueryDef, strSQL As String

Dim datStart As Date

datStart = #3-31-95#

Set dbs = CurrentDb

strSQL = "SELECT * FROM Orders WHERE OrderDate >= #" & datStart & "#;"

Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)

The next example creates a QueryDef object using a value in a control called OrderDate on an Orders form. Note that you provide the full reference to the control, and that you include the number signs that denote the date within the string.

Dim dbs As Database, qdf As QueryDef, strSQL As String

Set dbs = CurrentDb

strSQL = "SELECT * FROM Orders WHERE OrderDate >= #" & _ Forms!Orders!OrderDate & "#;"

Set qdf = dbs.CreateQueryDef("SecondQuarter", strSQL)


Changed and Removed Options in Microsoft Access 95

The following options existed in previous versions and have been changed in Microsoft Access 95.

Option	Notes
Syntax Checking Tab Stop Width Show Sort/Group Box	These options exist for compatibility with previous versions of Microsoft Access. Setting them has no effect, but won't generate an error.
Built-In Toolbars Available Objects Snap To Grid Show Grid Show Ruler Key Assignment Macro Move Enclosed Controls Control Wizards Can Customize Toolbars	These options can be set programmatically, but aren't available in the Options dialog box.
Default Gridlines Behavior	This option has been replaced by the Default Gridlines Horizontal and Default Gridlines Vertical options. You can still set it programmatically, however.
The following options have been removed in Microsoft Access 95. If you pass the following strings to the SetOption or GetOption methods, Microsoft Access will generate a run-time error.

First Week

First Weekday


ApplyFilter Method

The ApplyFilter method carries out the ApplyFilter action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.ApplyFilter [filtername] [, wherecondition]

The ApplyFilter method uses the following arguments.

Argument	Description

filtername	A string expression that is the valid name of a query in the current database

wherecondition	A string expression that is a valid SQL WHERE clause without the word WHERE

Remarks

You must include at least one of the two ApplyFilter arguments. If you enter a value for both arguments, wherecondition is applied to the filter.

The maximum length of the wherecondition argument is 32,768 characters (unlike the Where Condition action argument in the Macro window, whose maximum length is 256 characters).

If you specify the wherecondition argument and leave the filtername argument blank, you must include the filtername argument's comma.


ApplyFilter Method Example

This example uses the ApplyFilter method to display only records that contain the name King in the LastName field.

DoCmd.ApplyFilter , "[LastName] = 'King'"


Beep Method

The Beep method carries out the Beep action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Beep

This method uses no arguments.

Remarks

You can also use the Visual Basic Beep statement to cause your computer to sound a tone through its speaker.


CancelEvent Method

The CancelEvent method carries out the CancelEvent action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.CancelEvent

This method uses no arguments.

Remarks

The CancelEvent method has an effect only when it is run as the result of an event. This method cancels the event.

All events that can be canceled in Visual Basic have a Cancel argument. You can use this argument instead of the CancelEvent method to cancel the event. The KeyPress event and MouseDown event (for clicking the right mouse button only) can be canceled only in macros, not event procedures, so you must use the CancelEvent action in a macro to cancel these events.


Close Method

The Close method carries out the Close action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Close [objecttype, objectname], [save]

The Close method uses the following arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument

save	One of the following intrinsic constants:

acPrompt
acSaveYes
acSaveNo

If you leave this argument blank, the default (acPrompt) is assumed.

Remarks

If you leave the objecttype and objectname arguments blank, Microsoft Access closes the active window. If you specify the save argument and leave the objecttype and objectname arguments blank, you must include the objecttype and objectname arguments' commas.


Close Method Example

This example uses the Close method to close the form Order Review, saving any changes to the form without prompting.

DoCmd.Close acForm, "Order Review", acSaveYes


CopyObject Method

The CopyObject method carries out the CopyObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.CopyObject [destinationdatabase] [, newname] [, sourceobjecttype, sourceobjectname]

The CopyObject method uses the following arguments.

Argument	Description

destinationdatabase	A string expression that is the valid path and file name for the database you want to copy the object into. To select the current database, leave this argument blank.

If you execute Visual Basic code containing the CopyObject method in a library database and leave this argument blank, Microsoft Access copies the object into the library database.

newname	A string expression that is the new name for the object you want to copy. To use the same name if you are copying into another database, leave this argument blank.

sourceobjecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

sourceobjectname	A string expression that is the valid name of an object of the type selected with the sourceobjecttype argument.

If you execute Visual Basic code containing the CopyObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

You must include either the destinationdatabase or newname argument or both for this method.

If you leave the sourceobjecttype and sourceobjectname arguments blank, Microsoft Access copies the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action or SelectObject method with the In Database Window argument set to Yes (True).

If you specify the sourceobjecttype and sourceobjectname arguments but leave either the newname argument or the destinationdatabase argument blank, you must include the newname or destinationdatabase argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


 CopyObject Method Example

This example uses the CopyObject method to copy the Employees table and give it a new name in the current database.

DoCmd.CopyObject , "Employees Copy", acTable, "Employees"


DeleteObject Method

The DeleteObject method carries out the DeleteObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.DeleteObject [objecttype, objectname]

The DeleteObject method uses the following arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument.

If you run Visual Basic code containing the DeleteObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

If you leave the objecttype and objectname arguments blank, Microsoft Access deletes the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action or SelectObject method with the In Database Window argument set to Yes (True).


DeleteObject Method Example

This example deletes the specified table.

DoCmd.DeleteObject acTable, "Former Employees Table"


DoMenuItem Method

The DoMenuItem method carries out the DoMenuItem action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.DoMenuItem menubar, menuname, command [, subcommand] [, version]

The DoMenuItem method uses the following arguments.

Argument	Description

menubar	Use the intrinsic constant acFormBar for the menu bar in Form view.

For other views, switch to the Macro window, and use the number of the view in the Menu Bar argument list (count down the list, starting from 0).

menuname	You can use one of the following intrinsic constants:

acFile
acEditMenu
acRecordsMenu

You can use acRecordsMenu only for the Form view menu bar in Microsoft Access version 2.0 and Microsoft Access for Windows 95 databases.

For other menus, switch to the Macro window, and use the number of the menu in the Menu Name argument list (count down the list, starting from 0).

command	You can use one of the following intrinsic constants:

acNew
acSaveForm
acSaveFormAs
acSaveRecord
acUndo
acCut
acCopy
acPaste
acDelete
acSelectRecord
acSelectAllRecords
acObject
acRefresh

For other commands, switch to the Macro window, and use the number of the command in the Command argument list (count down the list, starting from 0).

subcommand	You can use one of the following intrinsic constants:

acObjectVerb
acObjectUpdate

The acObjectVerb constant represents the first command on the submenu of the Object command on the Edit menu. The type of object determines the first command on the submenu. For example, this command is Edit for a Paintbrush object that can be edited.

For other commands on submenus, switch to the Macro window, and use the number of the subcommand in the Subcommand argument list (count down the list, starting from 0).

version	Use the intrinsic constant acMenuVer70 for code written for Microsoft Access 95 databases, the intrinsic constant acMenuVer20 for code written for Microsoft Access version 2.0 databases, and the intrinsic constant acMenuVer1X for code written for Microsoft Access version 1.x databases. This argument is available only in Visual Basic.

Note   The default for this argument is acMenuVer1X, so that any code written for Microsoft Access version 1.x databases will run unchanged. If you're writing code for a Microsoft Access 95 or version 2.0 database and want to use the Microsoft Access 95 or version 2.0 menu commands with the DoMenuItem method, you must set this argument to acMenuVer70 or acMenuVer20.

Also, when you are counting down the lists for the Menu Bar, Menu Name, Command, and Subcommand action arguments in the Macro window to get the numbers to use for the arguments in the DoMenuItem method, you must use the Microsoft Access 95 lists if the version argument is acMenuVer70, the Microsoft Access version 2.0 lists if the version argument is acMenuVer20, and the Microsoft Access version 1.x lists if version is acMenuVer1X (or blank).

Remarks

The selections in the lists for the Menu Name, Command, and Subcommand action arguments in the Macro window depend on what you have selected for the previous arguments. You must use numbers or intrinsic constants that are appropriate for each menubar, menuname, command, and subcommand argument.

If you leave the subcommand argument blank but specify the version argument, you must include the subcommand argument's comma. If you leave the subcommand and version arguments blank, don't use a comma following the command argument.


DoMenuItem Method Example

This example uses the DoMenuItem method to carry out the Paste command on the Edit menu in Form view in a Microsoft Access for Windows 95 database.

DoCmd.DoMenuItem acFormBar, acEditMenu, acPaste, , acMenuVer70

The next example carries out the Tile command on the Window menu in Form view in a Microsoft Access version 2.0 database.

DoCmd.DoMenuItem acFormBar, 4, 0, , acMenuVer20


Echo Method (DoCmd Object)

The Echo method of the DoCmd object carries out the Echo action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Echo echoon [, statusbartext]

The Echo method uses the following arguments.

Argument	Description

echoon	Use True (-1) to turn echo on and False (0) to turn it off.

statusbartext	A string expression.

Remarks

If you leave the statusbartext argument blank, don't use a comma following the echoon argument.

If you turn echo off in Visual Basic, you must turn it back on, or it will remain off, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint. You may want to create a macro that turns echo on and then assign that macro to a key combination or a custom menu command. You could then use the key combination or menu command to turn echo on if it has been turned off in Visual Basic.

The Echo method of the DoCmd object was added to provide backwards compatibility for running the Echo action in Visual Basic code in Microsoft Access for Windows 95. It is recommended that you use the existing Echo method of the Application object instead. The Echo method of the DoCmd object is different from the Echo method of the Application object


Echo Method (DoCmd Object) Example

This example uses the Echo method to turn echo off and display the specified text in the status bar while your Visual Basic code is executing.

DoCmd.Echo False, "Visual Basic code is executing."


FindNext Method

The FindNext method carries out the FindNext action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.FindNext

This method uses no arguments.


FindRecord Method

The FindRecord method carries out the FindRecord action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.FindRecord findwhat [, match] [, matchcase] [, search] [, searchasformatted] [, onlycurrentfield] [, findfirst]

The FindRecord method uses the following arguments.

Argument	Description

findwhat	An expression that evaluates to text, a number, or a date. The expression contains the data to search for.

match	One of the following intrinsic constants:

acAnywhere
acEntire
acStart

If you leave this argument blank, the default (acEntire) is assumed.

matchcase	Use True (-1) for a case-sensitive search and False (0) for a search that is not case-sensitive. If you leave this argument blank, the default (False) is assumed.

search	One of the following intrinsic constants:

acUp
acDown
acSearchAll

If you leave this argument blank, the default (acSearchAll) is assumed.

searchasformatted	Use True to search for data as it is formatted and False to search for data as it is stored in the database. If you leave this argument blank, the default (False) is assumed.

onlycurrentfield	One of the following intrinsic constants:

acCurrent
acAll

If you leave this argument blank, the default (acCurrent) is assumed.

findfirst	Use True to start the search at the first record. Use False to start the search at the record following the current record. If you leave this argument blank, the default (True) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave one or more trailing arguments blank, don't use a comma following the last argument you specify.


FindRecord Method Example

This example finds the first occurrence in the records of the name Smith in the current field. It doesn't find occurrences of smith or Smithson.

DoCmd.FindRecord "Smith",, True,, True


GoToControl Method

The GoToControl method carries out the GoToControl action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.GoToControl controlname

The GoToControl method uses the following arguments.

Argument	Description

controlname	A string expression that is the name of a control on the active form or datasheet

Remarks

Use only the name of the control for the controlname argument, not the full syntax.

You can also use a variable declared as a Control data type for this argument:

Dim Ctl As Control
Set Ctl = Forms!Form1!Field3
DoCmd.GoToControl Ctl.Name

You can also use the SetFocus method to move the focus to a control on a form or any of its subforms, or to a field in an open table, query, or form datasheet. This is the preferred method for moving the focus in Visual Basic, especially to controls on subforms and nested subforms, because you can use the full syntax to specify the control you want to move to.


GoToControl Method Example

This example uses the GoToControl method to move the focus to the EmployeeID field.

DoCmd.GoToControl "EmployeeID"


GoToPage Method (DoCmd Object)

The GoToPage method of the DoCmd object carries out the GoToPage action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.GoToPage [pagenumber] [, right, down]

The GoToPage method uses the following arguments.

Argument	Description

pagenumber	A numeric expression that is a valid page number for the active form. If you leave this argument blank, the focus stays on the current page. You can use the right and down arguments to display the part of the page you want to see.

right	A numeric expression that is a valid horizontal offset for the page

down	A numeric expression that is a valid vertical offset for the page

Remarks

The units for the right and down arguments are twips.

If you specify the right and down arguments and leave the pagenumber argument blank, you must include the pagenumber argument's comma. If you don't specify the right and down arguments, don't use a comma following the pagenumber argument.

The GoToPage method of the DoCmd object was added to provide backwards compatibility for running the GoToPage action in Visual Basic code in Microsoft Access for Windows 95. It is recommended that you use the existing GoToPage method of the Form object instead. The GoToPage method of the DoCmd object is different from the GoToPage method of the Form object


GoToPage Method (DoCmd Object) Example

This example uses the GoToPage method to move the focus to the position specified by the horizontal and vertical offsets on the second page of the active form.

DoCmd.GoToPage 2, 1440, 567


GoToRecord Method

The GoToRecord method carries out the GoToRecord action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.GoToRecord [objecttype, objectname] [, record] [, offset]

The GoToRecord method uses the followng arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument.

record	One of the following intrinsic constants:

acPrevious
acNext
acFirst
acLast
acGoTo
acNewRec

If you leave this argument blank, the default (acNext) is assumed.

offset	A numeric expression that represents the number of records to move forward or backward if you specify acNext or acPrevious for the record argument, or the record to move to if you specify acGoTo for the record argument. The expression must result in a valid record number.

Remarks

If you leave the objecttype and objectname arguments blank, the active object is assumed.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave one or more trailing arguments blank, don't use a comma following the last argument you specify.


GoToRecord Method Example

This example uses the GoToRecord method to make the seventh record in the form Employees current.

DoCmd.GoToRecord acForm, "Employees", acGoTo, 7


Hourglass Method

The Hourglass method carries out the Hourglass action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.Hourglass hourglasson

The Hourglass method uses the following arguments.

Argument	Description

hourglasson	Use True (-1) to display the hourglass (or another icon you've chosen). Use False (0) to display the normal mouse pointer.


Hourglass Method Example

This example uses the Hourglass method to display an hourglass (or another icon you've chosen) while your Visual Basic code is executing.

DoCmd.Hourglass True


Maximize Method

The Maximize method carries out the Maximize action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Maximize

This method uses no arguments.


Minimize Method

The Minimize method carries out the Minimize action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Minimize

This method uses no arguments.


MoveSize Method

The MoveSize method carries out the MoveSize action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.MoveSize [ right] [, down] [, width] [, height]

The MoveSize method uses the following arguments.

Argument	Description

right	Numeric expression

down	Numeric expression

width	Numeric expression

height	Numeric expression

Remarks

You must include at least one argument for the MoveSize method. If you leave an argument blank, the current setting for the window is used.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave one or more trailing arguments blank, don't use a comma following the last argument you specify.

The units for the arguments are twips.


MoveSize Method Example

This example moves the active window and changes its height, but leaves its width unchanged.

DoCmd.MoveSize 1440, 2400, , 2000


OpenForm Method

The OpenForm method carries out the OpenForm action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenForm formname [, view] [, filtername] [, wherecondition] [, datamode] [, windowmode] [, openargs]

The OpenForm method uses the following arguments.

Argument	Description

formname	A string expression that is the valid name of a form in the current database.

If you execute Visual Basic code containing the OpenForm method in a library database, Microsoft Access looks for the form with this name first in the library database, then in the current database.

view	One of the following intrinsic constants:

acNormal
acDesign
acPreview
acFormDS

acNormal opens the form in Form view.

If you leave this argument blank, the default (acNormal) is assumed.

filtername	A string expression that is the valid name of a query in the current database.

wherecondition	A string expression that is a valid SQL WHERE clause without the word WHERE.

datamode	One of the following intrinsic constants:

acAdd
acEdit
acReadOnly

If you leave this argument blank, the default (acEdit) is assumed.

windowmode	One of the following intrinsic constants:

acNormal
acHidden
acIcon
acDialog

If you leave this argument blank, the default (acNormal) is assumed.

openargs	A string expression. This expression is used to set the form's OpenArgs property. This setting can then be used by code in a form module, such as the Open event procedure. The OpenArgs property can also be referred to in macros and expressions.

For example, suppose that the form you open is a continuous-form list of clients. If you want the focus to move to a specific client record when the form opens, you can specify the client name with openargs.

This argument is available only in Visual Basic.

Remarks

The maximum length of the wherecondition argument is 32,768 characters (unlike the Where Condition action argument in the Macro window, whose maximum length is 256 characters).

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


OpenForm Method Example

This example opens the Employees form in Form view and displays only records with King in the LastName field. The displayed records can be edited, and new records can be added.

DoCmd.OpenForm "Employees", , ,"[LastName] = 'King'"


OpenModule Method

The OpenModule method carries out the OpenModule action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenModule [modulename] [, procedurename]

The OpenModule method uses the following arguments.

Argument	Description

modulename	A string expression that is the valid name of the Visual Basic module you want to open. If you leave this argument blank, Microsoft Access searches all the standard modules in the database for the procedure you selected with the procedurename argument and opens the module containing the procedure to that procedure.

If you execute Visual Basic code containing the OpenModule method in a library database, Microsoft Access looks for the module with this name first in the library database, then in the current database.

procedurename	A string expression that is the valid name for the procedure you want to open the module to. If you leave this argument blank, the module opens to the Declarations section.

Remarks

You must include at least one of the two OpenModule arguments. If you enter a value for both arguments, Microsoft Access opens the specified module at the specified procedure.

If you leave the procedurename argument blank, don't use a comma following the modulename argument.


OpenModule Method Example

This example opens the Utility Functions module to the IsLoaded() Function procedure.

DoCmd.OpenModule "Utility Functions","IsLoaded"


OpenQuery Method

The OpenQuery method carries out the OpenQuery action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenQuery queryname [, view] [, datamode]

The OpenQuery method uses the following arguments.

Argument	Description

queryname	A string expression that is the valid name of a query in the current database.

If you execute Visual Basic code containing the OpenQuery method in a library database, Microsoft Access looks for the query with this name first in the library database, then in the current database.

view	One of the following intrinsic constants:

acNormal
acDesign
acPreview

If queryname is the name of a select, crosstab, union, or pass-through query whose ReturnsRecords property is set to -1, acNormal displays the query's result set. If queryname refers to an action, data-definition, or pass-through query whose ReturnsRecords property is set to 0, acNormal runs the query.

If you leave this argument blank, the default (acNormal) is assumed.

datamode	One of the following intrinsic constants:

acAdd
acEdit
acReadOnly

If you leave this argument blank, the default (acEdit) is assumed.

Remarks

If you specify the datamode argument and leave the view argument blank, you must include the view argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


OpenQuery Method Example

This example opens Sales Totals Query in Datasheet view and enables the user to view but not to edit or add records.

DoCmd.OpenQuery "Sales Totals Query", , acReadOnly


OpenReport Method

The OpenReport method carries out the OpenReport action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenReport reportname [, view] [, filtername] [, wherecondition]

The OpenReport method uses the following arguments.

Argument	Description

reportname	A string expression that is the valid name of a report in the current database.

If you execute Visual Basic code containing the OpenReport method in a library database, Microsoft Access looks for the report with this name first in the library database, then in the current database.

view	One of the following intrinsic constants:

acNormal
acDesign
acPreview

acNormal prints the report immediately. If you leave this argument blank, the default (acNormal) is assumed.

filtername	A string expression that is the valid name of a query in the current database.

wherecondition	A string expression that is a valid SQL WHERE clause without the word WHERE.

Remarks

The maximum length of the wherecondition argument is 32,768 characters (unlike the Where Condition action argument in the Macro window, whose maximum length is 256 characters).

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave one or more trailing arguments blank, don't use a comma following the last argument you specify.


OpenReport Method Example

This example prints Sales Report using the existing query Report Filter.

DoCmd.OpenReport "Sales Report", acNormal, "Report Filter"


OpenTable Method

The OpenTable method carries out the OpenTable action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OpenTable tablename [, view] [, datamode]

The OpenTable method uses the following arguments.

Argument	Description

tablename	A string expression that is the valid name of a table in the current database.

If you execute Visual Basic code containing the OpenTable method in a library database, Microsoft Access looks for the table with this name first in the library database, then in the current database.

view	One of the following intrinsic constants:

acNormal
acDesign
acPreview

acNormal opens the table in Datasheet view.

If you leave this argument blank, the default (acNormal) is assumed.

datamode	One of the following intrinsic constants:

acAdd
acEdit
acReadOnly

If you leave this argument blank, the default (acEdit) is assumed.

Remarks

If you specify the datamode argument and leave the view argument blank, you must include the view argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


OpenTable Method Example

This example opens the Employees table in Print Preview.

DoCmd.OpenTable "Employees", acPreview


OutputTo Method

The OutputTo method carries out the OutputTo action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.OutputTo objecttype [, objectname] [, outputformat] [, outputfile] [, autostart]

The OutputTo method uses the following arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acModule

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument. If you want to output the active object, specify the object's type for the objecttype argument and leave this argument blank.

If you execute Visual Basic code containing the OutputTo method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

outputformat	One of the following intrinsic constants:

acFormatXLS
acFormatRTF
acFormatTXT

If you leave this argument blank, Microsoft Access prompts you for the output format.

outputfile	A string expression that is the full name, including the path, of the file you want to output the object to.

If you leave this argument blank, Microsoft Access prompts you for an output file name.

autostart	Use True (-1) to start the appropriate Windows-based application immediately, with the file specified by outputfile loaded. Use False (0) if you don't want to start the application.

If you leave this argument blank, the default (False) is assumed.

Remarks

Modules can be output only in MS-DOS Text format, so if you specify acModule for objecttype, you must specify acFormatTXT for outputformat.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


OutputTo Method Example

This example outputs the Employees table in rich-text format (.rtf) to the Employee.rtf file and immediately opens the file in Microsoft Word for Windows.

DoCmd.OutputTo acTable, "Employees", acFormatRTF, "Employee.rtf", True


PrintOut Method

The PrintOut method carries out the PrintOut action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.PrintOut [printrange] [, pagefrom, pageto] [, printquality] [, copies] [, collatecopies]

The PrintOut method uses the following arguments.

Argument	Description

printrange	One of the following intrinsic constants:

acPrintAll
acSelection
acPages

If you leave this argument blank, the default (acPrintAll) is assumed.

pagefrom	A numeric expression that is a valid page number in the active form or datasheet. This argument is required if you specify acPages for the printrange argument.

pageto	A numeric expression that is a valid page number in the active form or datasheet. This argument is required if you specify acPages for the printrange argument.

printquality	One of the following intrinsic constants:

acHigh
acMedium
acLow
acDraft

If you leave this argument blank, the default (acHigh) is assumed.

copies	A numeric expression. If you leave this argument blank, the default (1) is assumed.

collatecopies	Use True (-1) to collate copies and False (0) to print without collating. If you leave this argument blank, the default (True) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave one or more trailing arguments blank, don't use a comma following the last argument you specify.


PrintOut Method Example

This example prints two collated copies of the first four pages of the active form or datasheet.

DoCmd.PrintOut acPages, 1, 4, , 2


Quit Method (DoCmd Object)

The Quit method of the DoCmd object carries out the Quit action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Quit [options]

The Quit method uses the following arguments.

Argument	Description

options	One of the following intrinsic constants:

acPrompt
acSaveYes
acSaveNo
acExit

If you leave this argument blank, the default (acSaveYes) is assumed.

Remarks

The Quit method of the DoCmd object was added to provide backwards compatibility for running the Quit action in Visual Basic code in Microsoft Access version 7.0. It is recommended that you use the existing Quit method of the Application object instead.


Quit Method (DoCmd Object) Example

This example displays a dialog box that asks if you want to save any changed objects before you quit Microsoft Access.

DoCmd.Quit acPrompt


Rename Method

The Rename method carries out the Rename action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Rename newname [, objecttype, oldname]

The Rename method uses the following arguments.

Argument	Description

newname	A string expression that is the new name for the object you want to rename. The name must follow the object-naming rules for Microsoft Access objects.

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

oldname	A string expression that is the valid name of an object of the type specified by the objecttype argument.

If you execute Visual Basic code containing the Rename method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Remarks

If you leave the objecttype and oldname arguments blank, Microsoft Access renames the object selected in the Database window. To select an object in the Database window, you can use the SelectObject action or SelectObject method with the In Database Window argument set to Yes (True).

If you leave the objecttype and oldname arguments blank, don't use a comma following the newname argument.


Rename Method Example

This example renames the Employees table using the specified name.

DoCmd.Rename "Old Employees Table", acTable, "Employees"


RepaintObject Method

The RepaintObject method carries out the RepaintObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.RepaintObject [objecttype, objectname]

The RepaintObject method uses the following arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument.

Remarks

Using the RepaintObject method with no arguments repaints the active window.

The RepaintObject method of the DoCmd object was added to provide backwards compatibility for running the RepaintObject action in Visual Basic code in Microsoft Access for Windows 95. If you want to repaint a form, it is recommended that you use the existing Repaint method of the Form object instead.


RepaintObject Method Example

This example repaints the form Customers.

DoCmd.RepaintObject acForm, "Customers"


Requery Method (DoCmd Object)

The Requery method of the DoCmd object carries out the Requery action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.Requery [controlname]

The Requery method uses the following arguments.

Argument	Description

controlname	A string expression that is the name of a control on the active object

Remarks

Use only the name of the control for the controlname argument, not the full syntax.

You can also use a variable declared as a Control data type for this argument:

Dim LstBox As Control
Set LstBox = Forms!Form1!Field3
DoCmd.Requery LstBox.Name

The Requery method of the DoCmd object is different from the Requery method in Visual Basic. The Requery method of the DoCmd object was added to provide backwards compatibility for running the Requery action in Visual Basic code in Microsoft Access for Windows 95. If you want to requery a control that is not on the active object, you must use the Requery method in Visual Basic, not the Requery action or its corresponding Requery method of the DoCmd object. The Requery method in Visual Basic is faster than the Requery action or the DoCmd Requery method. In addition, when you use the Requery action or the DoCmd Requery method, Microsoft Access closes the query and reloads it from the database, but when you use the Requery method, Microsoft Access reruns the query without closing and reloading it. Note that the Requery method for DAO objects works the same way as the Microsoft Access Requery method.


Requery Method (DoCmd Object) Example

This example uses the Requery method to update the EmployeeList control.

DoCmd.Requery "EmployeeList"


Restore Method

The Restore method carries out the Restore action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.Restore

This method uses no arguments.


RunMacro Method

The RunMacro method carries out the RunMacro action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.RunMacro macroname [, repeatcount] [, repeatexpression]

The RunMacro method uses the following arguments.

Argument	Description

macroname	A string expression that is the valid name of a macro in the current database.

If you execute Visual Basic code containing the RunMacro method in a library database, Microsoft Access looks for the macro with this name in the library database and doesn't look for it in the current database.

repeatcount	A numeric expression that evaluates to an integer, which is the number of times the macro will run.

repeatexpression	A numeric expression that is evaluated each time the macro runs. When it evaluates to False (0), the macro stops running.

Remarks

You can use "macrogroupname.macroname" for the macroname argument to run a particular macro in a macro group.

If you specify the repeatexpression argument and leave the repeatcount argument blank, you must include the repeatcount argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


RunMacro Method Example

This example runs the macro Print Sales.

DoCmd.RunMacro "Print Sales"


RunSQL Method

The RunSQL method carries out the RunSQL action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.RunSQL sqlstatement

The RunSQL method uses the following arguments.

Argument	Description

sqlstatement	A string expression that is a valid SQL statement for an action query or a data-definition query. It uses an INSERT INTO, DELETE, SELECT...INTO, UPDATE, CREATE TABLE, ALTER TABLE, DROP TABLE, CREATE INDEX, or DROP INDEX statement. Include an IN clause if you want to access another database.

Remarks

The maximum length of the sqlstatement argument is 32,768 characters (unlike the SQL Statement action argument in the Macro window, whose maximum length is 256 characters).


RunSQL Method Example

This example updates the Employees table, changing each sales manager's title to Regional Sales Manager.

DoCmd.RunSQL "UPDATE Employees " & _

"SET Employees.Title = 'Regional Sales Manager' " & _

"WHERE Employees.Title = 'Sales Manager';"


Save Method

The Save method carries out the Save action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.Save [objecttype, objectname]

The Save method uses the following arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument

Remarks

If you leave the objecttype and objectname arguments blank, Microsoft Access saves the active object. If you leave the objecttype argument blank, but enter a name in the objectname argument, Microsoft Access saves the active object with the specified name. If you enter an object type in the objecttype argument, you must enter an existing object's name in the objectname argument.

If you leave the objecttype argument blank, but enter a name in the objectname argument, you must include the objecttype argument's comma.

The Save method, whether it is executed in the current database or in a library database, always saves the specified object or the active object in the database in which the object was created.


Save Method Example

This example uses the Save method to save the active object (a form) with the new name "New Employees Form".

DoCmd.Save , "New Employees Form"


SelectObject Method

The SelectObject method carries out the SelectObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.SelectObject objecttype, objectname [, indatabasewindow]

The SelectObject method uses the following arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument.

indatabasewindow	Use True (-1) to select the object in the Database window. Use False (0) to select an object that is already open. If you leave this argument blank, the default (False) is assumed.

Remarks

If you leave the indatabasewindow argument blank, don't use a comma following the objectname argument.


SelectObject Method Example

This example selects the form Customers in the Database window.

DoCmd.SelectObject acForm, "Customers", True


SendObject Method

The SendObject method carries out the SendObject action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.SendObject [objecttype] [, objectname] [, outputformat] [, to] [, cc] [, bcc] [, subject] [, messagetext] [, editmessage]

The SendObject method uses the following arguments.

Argument	Description

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acModule

objectname	A string expression that is the valid name of an object of the type selected with the objecttype argument. If you want to include the active object in the mail message, specify the object's type with the objecttype argument and leave this argument blank. If you leave both the objecttype and objectname arguments blank, Microsoft Access sends a message to the electronic mail application without a database object.

If you execute Visual Basic code containing the SendObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

outputformat	One of the following intrinsic constants:

acFormatXLS
acFormatRTF
acFormatTXT

If you leave this argument blank, Microsoft Access prompts you for the output format.

to	A string expression that lists the recipients whose names you want to put on the To line in the mail message.

Separate the recipient names you specify in this argument and in the cc and bcc arguments with a semicolon (;) or with the list separator set in the Number tab of the Regional Settings properties sheet in the Windows Control Panel. If Microsoft Access can't identify the recipient names, it doesn't send the message.

If you leave this argument blank, Microsoft Access prompts you for the recipients.

cc	A string expression that lists the recipients whose names you want to put on the Cc line in the mail message. If you leave this argument blank, the Cc line in the mail message is blank.

bcc	A string expression that lists the recipients whose names you want to put on the Bcc line in the mail message. If you leave this argument blank, the Bcc line in the mail message is blank.

subject	A string expression containing the text you want to put on the Subject line in the mail message. If you leave this argument blank, the Subject line in the mail message is blank.

messagetext	A string expression containing the text you want to include in the body of the mail message, after the object. If you leave this argument blank, the object is all that is included in the body of the mail message.

editmessage	Use True (-1) to open the electronic mail application immediately with the message loaded, so the message can be edited. Use False (0) to send the message without editing it. If you leave this argument blank, the default (True) is assumed.

Remarks

Modules can be sent only in MS-DOS Text format, so if you specify acModule for the objecttype argument, you must specify acFormatTXT for the outputformat argument.

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


SendObject Method Example

This example includes the Employees table in a mail message in Microsoft Excel format and specifies To, Cc, and Subject lines in the mail message. The mail message is sent immediately, without editing.

DoCmd.SendObject acTable, "Employees", acFormatXLS, _

"Nancy Davolio; Andrew Fuller", "Joan Weber", , _

"Current Spreadsheet of Employees", , False


SetMenuItem Method

The SetMenuItem method carries out the SetMenuItem action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.SetMenuItem menuindex [, commandindex] [, subcommandindex] [, flag]

The SetMenuItem method uses the following arguments.

Argument	Description

menuindex	An integer, counting from 0, that is the valid index of a menu on the custom menu bar or global menu bar for the active window, as defined in the menu bar macro for the custom menu bar or global menu bar.

If you select a menu with this argument and leave the commandindex and subcommandindex arguments blank (or set them to -1), you can enable or disable the menu name itself. You can't, however, check or uncheck a menu name (Microsoft Access ignores the acMenuCheck and acMenuUncheck settings for the flag argument for menu names).

commandindex	An integer, counting from 0, that is the valid index of a command on the menu selected with the menuindex argument, as defined in the macro group that defines the selected menu for the custom menu bar or global menu bar for the active window.

subcommandindex	An integer, counting from 0, that is the valid index of a subcommand in the submenu selected with the commandindex argument, as defined in the macro group that defines the selected submenu for the custom menu bar or global menu bar for the active window.

flag	One of the following intrinsic constants:

acMenuUngray
acMenuGray
acMenuUncheck
acMenuCheck

If you leave this argument blank, the default (acMenuUngray) is assumed.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


SetMenuItem Method Example

This example uses the SetMenuItem method to disable the second command in the first menu on the custom menu bar for the active window.

DoCmd.SetMenuItem 0, 1, , acMenuGray


SetWarnings Method

The SetWarnings method carries out the SetWarnings action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.SetWarnings warningson

The SetWarnings method uses the following arguments.

Argument	Description

warningson	Use True (-1) to turn on the display of system messages and False (0) to turn it off.

Remarks

If you turn the display of system messages off in Visual Basic, you must turn it back on, or it will remain off, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint. You may want to create a macro that turns the display of system messages on and then assign that macro to a key combination or a custom menu command. You could then use the key combination or menu command to turn the display of system messages on if it has been turned off in Visual Basic.


SetWarnings Method Example

This example turns the display of system messages off.

DoCmd.SetWarnings False


ShowAllRecords Method

The ShowAllRecords method carries out the ShowAllRecords action in Visual Basic. For more information on how the action works, see the action topic.

Syntax

DoCmd.ShowAllRecords

This method uses no arguments.


ShowToolbar Method

The ShowToolbar method carries out the ShowToolbar action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.ShowToolbar toolbarname [, show]

The ShowToolbar method uses the following arguments.

Argument	Description

toolbarname	A string expression that is the valid name of a Microsoft Access built-in toolbar or a custom toolbar you've created.

If you execute Visual Basic code containing the ShowToolbar method in a library database, Microsoft Access looks for the toolbar with this name first in the library database, then in the current database.

show	One of the following intrinsic constants:

acToolbarYes
acToolbarWhereApprop
acToolbarNo

If you leave this argument blank, the default (acToolbarYes) is assumed.

Remarks

If you leave the show argument blank, don't use a comma following the toolbarname argument.


ShowToolbar Method Example

This example displays the custom toolbar named CustomToolbar in all Microsoft Access windows that become active.

DoCmd.ShowToolbar "CustomToolbar", acToolbarYes


TransferDatabase Method

The TransferDatabase method carries out the TransferDatabase action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.TransferDatabase [transfertype], databasetype, databasename [, objecttype], source, destination [, structureonly] [, saveloginid]

The TransferDatabase method uses the following arguments.

Argument	Description

transfertype	One of the following intrinsic constants:

acImport
acExport
acLink

If you leave this argument blank, the default (acImport) is assumed.

databasetype	A string expression that is the name of one of the types of databases you can use to import, export, or link data.

In the Macro window, you can view the database types in the list for the Database Type action argument of the TransferDatabase action.

databasename	A string expression that is the full name, including the path, of the database you want to use to import, export, or link data.

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

This is the type of object whose data you want to import, export, or link. You can specify an object other than acTable only if you are importing or exporting data between two Microsoft Access databases. If you are exporting the results of a Microsoft Access select query to another type of database, specify acTable for this argument.

If you leave this argument blank, the default (acTable) is assumed.

source	A string expression that is the name of the object whose data you want to import, export, or link.

destination	A string expression that is the name of the imported, exported, or linked object in the destination database.

structureonly	Use True (-1) to import or export only the structure of a database table. Use False (0) to import or export the structure of the table and its data.

If you leave this argument blank, the default (False) is assumed.

saveloginid	Use True to store the login identification (ID) and password for an ODBC database in the connection string for a linked table from the database. If you do this, you don't have to log in each time you open the table. Use False if you don't want to store the login ID and password.

If you leave this argument blank, the default (False) is assumed.

This argument is available only in Visual Basic.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.

The administrator of an ODBC database can disable the feature provided by the saveloginid argument, requiring all users to enter the login ID and password each time they connect to the ODBC database.


TransferDatabase Method Example

This example imports the NW Sales for April report from the Microsoft Access database NWSales.mdb into the Corporate Sales for April report in the current database.

DoCmd.TransferDatabase acImport, "Microsoft Access", _

"C:\DBS\NWSales.mdb", acReport, "NW Sales for April", _

"Corporate Sales for April"

This example links the ODBC database table Authors to the current database.

DoCmd.TransferDatabase acLink, "ODBC Database", _

"ODBC;DSN=DataSource1;UID=User2;PWD=www;LANGUAGE=us_english;" _

& "DATABASE=pubs", acTable, "Authors", "dboAuthors"


TransferSpreadsheet Method

The TransferSpreadsheet method carries out the TransferSpreadsheet action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.TransferSpreadsheet [transfertype] [, spreadsheettype], tablename, filename [, hasfieldnames] [, range]

The TransferSpreadsheet method uses the following arguments.

Argument	Description

transfertype	One of the following intrinsic constants:

acImport
acExport
acLink

If you leave this argument blank, the default (acImport) is assumed

spreadsheettype	One of the following numeric settings:

0  Microsoft Excel version 3.0
2  Lotus (WK1)
3  Lotus (WK3)
4  Lotus (WJ2) -- Japanese version only
5  Microsoft Excel version 5.0 and version 7.0
6  Microsoft Excel version 4.0
7  Lotus (WK4)

Note   You can import, export, and link spreadsheet data from Microsoft Excel spreadsheets, but you can only import and export data from Lotus spreadsheets. Microsoft Access also no longer supports importing, exporting, or linking data from Lotus (WKS) or Microsoft Excel version 2.0 spreadsheets.

If you leave this argument blank, the default (Microsoft Excel 3) is assumed.

tablename	A string expression that is the name of the Microsoft Access table you want to import spreadsheet data into, export spreadsheet data from, or link spreadsheet data to, or the Microsoft Access select query whose results you want to export to a spreadsheet.

filename	A string expression that is the file name and path of the spreadsheet you want to import from, export to, or link to.

hasfieldnames	Use True (-1) to use the first row of the spreadsheet as field names when importing, exporting, or linking. Use False (0) to treat the first row of the spreadsheet as normal data. If you leave this argument blank, the default (False) is assumed.

range	A string expression that is a valid range of cells or the name of a range in the spreadsheet. This argument applies only to importing. Leave this argument blank to import the entire spreadsheet.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


TransferSpreadsheet Method Example

This example imports the data from the specified range of the Lotus spreadsheet Newemps.wk3 into the Microsoft Access Employees table. It uses the first row of the spreadsheet as field names.

DoCmd.TransferSpreadsheet acImport, 3, _ "Employees",C:\Lotus\Newemps.wk3", True, "A1:G12"


TransferText Method

The TransferText method carries out the TransferText action in Visual Basic. For more information on how the action and its arguments work, see the action topic.

Syntax

DoCmd.TransferText [transfertype] [, specificationname], tablename, filename [, hasfieldnames]

The TransferText method uses the following arguments.

Argument	Description

transfertype	One of the following intrinsic constants:

acImportDelim
acImportFixed
acExportDelim
acExportFixed
acExportMerge
acLinkDelim
acLinkFixed

If you leave this argument blank, the default (acImportDelim) is assumed.

specificationname	A string expression that is the name of an import or export specification you have created and saved in the current database.

This argument is required for fixed-width text files. For delimited text files and Microsoft Word for Windows mail merge data files, you can leave this argument blank to select the default import/export specifications.

tablename	A string expression that is the name of the Microsoft Access table you want to import text data to, export text data from, or link text data to, or the Microsoft Access select query whose results you want to export to a text file.

filename	A string expression that is the full name, including the path, of the text file you want to import from, export to, or link to.

hasfieldnames	Use True (-1) to use the first row of the text file as field names when importing, exporting, or linking. Use False (0) to treat the first row of the text file as normal data. If you leave this argument blank, the default (False) is assumed.

This argument is ignored for Word for Windows mail merge data files, which must always contain the field names in the first row.

Remarks

You can leave an optional argument blank in the middle of the syntax, but you must include the argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.


TransferText Method Example

This example exports the data from the Microsoft Access table External Report to the delimited text file April.doc using the specification Standard Output.

DoCmd.TransferText acExportDelim, "Standard Output", _

"External Report", "C:\Txtfiles\April.doc"


BuildCriteria Method

The BuildCriteria method returns a parsed criteria string as it would appear in the query design grid or in Filter By Form mode. For example, you may want to set a form's Filter property based on varying criteria from the user. You can use the BuildCriteria method to construct the criteria string argument for the Filter property.

Syntax

BuildCriteria(field, fieldtype, expression)

The BuildCriteria method uses the following arguments.

Argument	Description

field	A string expression identifying the field for which you wish to define criteria.

fieldtype	An intrinsic constant denoting the data type of the field. For a list of possible field data types, see the data access Type property.

expression	A string expression identifying the criteria to be parsed.

The BuildCriteria method returns a string.

Remarks

The BuildCriteria method enables you to easily construct criteria for a filter based on user input. It parses the expression argument in the same way that the expression would be parsed had it been entered in the query design grid or in Filter By Form mode.

For example, a user creating a query on an Orders table might restrict the result set to orders placed after January 1, 1995, by setting criteria on an OrderDate field. The user might enter an expression such as the following one in the criteria cell beneath the OrderDate field.

>1-1-95

Microsoft Access automatically parses this expression and returns the following expression.

>#1/1/95#

The BuildCriteria method provides the same parsing from Visual Basic code. For example, to return the correctly parsed string shown above, you can supply the following arguments to the BuildCriteria method.

Dim strCriteria As String

strCriteria = BuildCriteria("OrderDate", dbDate, ">1-1-95")

Since you need to supply criteria for the Filter property in correctly parsed form, you can use the BuildCriteria method to construct a correctly parsed string.

You can use the BuildCriteria method to construct a string with multiple criteria if those criteria refer to the same field. For example, you can use the BuildCriteria method with the following arguments to construct a string with multiple criteria relating to the OrderDate field.

strCriteria = BuildCriteria("OrderDate", dbDate, ">1-1-95 and <5-1-95")

This example returns the following criteria string.

OrderDate>#1/1/95# And OrderDate<#5/1/95#

However, if you wish to construct a criteria string referring to multiple fields, you must create the strings and concatenate them yourself. For example, if you wish to construct criteria for a filter to show records for orders placed after 1-1-95 and for which freight is less than $50, you would need to use the BuildCriteria method twice and concatenate the resulting strings.


BuildCriteria Method Example

The following example prompts the user to enter the first few letters of a product's name, then uses the BuildCriteria method to construct a criteria string based on the user's input. Next, the procedure provides this string as an argument to the Filter property of a Products form. Finally, the FilterOn property is set to apply the filter.

Sub SetFilter()

Dim frm As Form, strMsg As String

Dim strInput As String, strFilter As String

' Open Products form in Form view.

DoCmd.OpenForm "Products"

' Return Form variable pointing to Products form.

Set frm = Forms!Products

strMsg = "Enter one or more letters of product name " _

& "followed by an asterisk."

' Prompt user for input.

strInput = InputBox(strMsg)

' Build criteria string.

strFilter = BuildCriteria("ProductName", dbText, strInput)

' Set Filter property to apply filter.

frm.Filter = strFilter

' Set FilterOn property; form now shows filtered records.

frm.FilterOn = True

End Sub


CloseCurrentDatabase Method

You can use the CloseCurrentDatabase method to close the current database from another application that has opened a database through OLE Automation. For example, you might use this method from Microsoft Excel to close the database currently open in the Microsoft Access window before opening another database.

Syntax

application.CloseCurrentDatabase

The CloseCurrentDatabase method uses the following argument.

Argument	Description

application	The Application object.

Remarks

The CloseCurrentDatabase method is useful when you have opened a Microsoft Access database from another application through OLE Automation. Once you have created an instance of Microsoft Access from another application, you must also create a new database or specify an existing database to open. This database opens in the Microsoft Access window.

If you use the CloseCurrentDatabase method to close the database that is open in the current instance of Microsoft Access, you can then open a different database without having to create another instance of Microsoft Access.

Note   Don't confuse the CloseCurrentDatabase method with the data access Close method. The Close method closes a Database object variable, causing the variable to go out of scope, but it doesn't actually close the database open in the Microsoft Access window. The CloseCurrentDatabase method closes the database that is open in the Microsoft Access window.


CloseCurrentDatabase Method Example

The following example opens a Microsoft Access database from another application through OLE Automation, creates a new form and saves it, then closes the database.

You can enter this code in a Visual Basic module in any application that can act as an OLE Automation controller. For example, you might run the following code from Microsoft Excel or Microsoft Visual Basic.

When the variable pointing to the Application object goes out of scope, the instance of Microsoft Access that it represents closes as well. Therefore, you should declare this variable at the module level.

' Enter following in Declarations section of module.

' From Microsoft Excel, use "Dim appAccess As Object".

Dim appAccess As Access.Application

Sub GetTableNames()

Dim dbs As Database, frm As Form, strDB As String

' Initialize string to database path

strDB = "C:\MSOffice\Access\Samples\Northwind.mdb"

' Create new instance of Microsoft Access.

Set appAccess = CreateObject("Access.Application.7")

' Open database in Microsoft Access window.

appAccess.OpenCurrentDatabase strDB

' Create new form.

Set frm = appAccess.CreateForm

' Save new form.

appAccess.DoCmd.Save , "NewForm1"

' Close currently open database.

appAccess.CloseCurrentDatabase

End Sub


DefaultControl Method

The DefaultControl method returns a Control object with which you can set the default properties for a particular type of control on a particular form. For example, before you create a text box on a form, you might want to set the default properties for the text box. Then you can create a number of text boxes that have the same base property settings, rather than having to set properties for each text box individually once it has been created.

Syntax

Set control = object.DefaultControl(controltype)

The DefaultControl method uses the following arguments.

Argument	Description

control	A Control object for which the default properties are to be set.

object	A Form or Report object on which controls are to be created. The default property settings defined for a type of control apply only to controls of the same type created on this form or report.

controltype	An intrinsic constant indicating the type of control for which default property settings are to be set.

Remarks

The DefaultControl method enables you to set a control's default properties from code. Once you have set the default properties for a particular type of control, each subsequently created control of that type will have the same default values.

For example, if you set the FontSize property of the default command button to 12, each new command button will have a font size of 12 points.

Not all of a control's properties are available as default properties. The default properties available for a control depend on the type of control.

The DefaultControl method returns a Control object of the type specified by the controltype argument. This Control object doesn't represent an actual control on a form, but rather a default control that is a template for all subsequently created controls of that type. You set the default control properties for the Control object returned by the DefaultControl method in the same manner that you would set properties for an individual control on a form.

For a list of intrinsic constants that can be passed as the controltype argument, see the CreateControl function. These constants are also listed in the Constants module of the Microsoft Access library in the Object Browser.

The DefaultControl method applies only to form Design view or report Design view. If you try to apply this method to a form or report that is not in Design view, a run-time error will result.

If you try to set a property that can't be set as a default property with the DefaultControl method, a run-time error will result. To determine which properties can be default properties, enumerate the Properties collection of the Control object returned by the DefaultControl method.


DefaultControl Method Example

The following example creates a new form and uses the DefaultControl method to return a control object representing the default command button. The procedure sets some of the default properties for the command button, then creates a new command button on the form.

Sub SetDefaultProperties()

Dim frm As Form, ctlDefault As Control, ctlNew As Control

' Create new form.

Set frm = CreateForm

' Return Control object representing default command button.

Set ctlDefault = frm.DefaultControl(acCommandButton)

' Set some default properties.

With ctlDefault

.FontWeight = 700

.FontSize = 12

.Width = 3000

.Height = 1000

End With

' Create new command button.

Set ctlNew = CreateControl(frm.Name, acCommandButton, , , , 500, 500)

' Set control's caption.

ctlNew.caption = "New Command Button"

' Restore form.

DoCmd.Restore

End Sub


SizeToFit Method

You can use the SizeToFit method to size a control so it fits the text or image that it contains. For example, you can apply the SizeToFit method to a command button that is too small to display all the text in its Caption property.

Syntax

control.SizeToFit

The SizeToFit method uses the following argument.

Argument	Description

control	A control that displays text or an image, including the label, toggle button, command button, image, unbound object frame, and subform/subreport controls.

Remarks

Using the SizeToFit method is equivalent to selecting a control on a form or report, pointing to Size on the Format menu, and clicking To Fit. You can apply the SizeToFit method to controls only in form Design view or report Design view.

The SizeToFit method will make a control larger or smaller, depending on the size of the text or image it contains.

Use the SizeToFit method in conjunction with the CreateControl function to size new controls that you have created in code.

Note   Not all controls that contain text or an image can be sized by the SizeToFit method. Several controls are bound to data that can vary in size from one record to the next. These controls include the text box, list box, combo box, and bound object frame controls.


SizeToFit Method Example

The following example creates a new form and creates a new command button on the form. The procedure then sets the control's Caption property and sizes the control to fit the caption.

Sub SizeNewControl()

Dim frm As Form, ctl As Control

' Create new form.

Set frm = CreateForm

' Create new command button.

Set ctl = CreateControl(frm.Name, acCommandButton, , , , 500, 500)

' Restore form.

DoCmd.Restore

' Set control's Caption property.

ctl.Caption = "Extremely Long Control Caption"

' Size control to fit caption.

ctl.SizeToFit

End Sub


DefaultWorkspaceClone Method

You can use the DefaultWorkspaceClone method to create a new Workspace object without requiring the user to log in again. For example, if you need to conduct two sets of transactions simultaneously in separate workspaces, you can use the DefaultWorkspaceClone method to create a second Workspace object with the same user name and password without prompting the user for this information again.

Syntax

Application.DefaultWorkspaceClone

The DefaultWorkspaceClone method uses the following argument.

Argument	Description

Application	The Application object.

Remarks

The DefaultWorkspaceClone method creates a clone of the default Workspace object in Microsoft Access. The properties of the Workspace object clone have settings identical to those of the default Workspace object, except for the Name property setting. For the default Workspace object, the value of the Name property is always #Default Workspace#. For the cloned Workspace object, it is #CloneAccess#.

The UserName property of the default Workspace object indicates the name under which the current user logged in. The Workspace object clone is equivalent to the Workspace object that would be created if the same user logged in again with the same password.


DefaultWorkspaceClone Method Example

The following example clones the default workspace, then enumerates the properties of each workspace.

Sub CloneWorkspace()

Dim wrkDefault As Workspace, wrkClone As Workspace

Dim prp As Property

' Get default workspace.

Set wrkDefault = DBEngine.Workspaces(0)

' Clone default workspace.

Set wrkClone = Application.DefaultWorkspaceClone

' Enumerate properties of each workspace.

For Each prp In wrkDefault.Properties

Debug.Print ">>>"; prp.Name; "   "; prp.Value

Next prp

For Each prp In wrkClone.Properties

Debug.Print ">>>"; prp.Name; "   "; prp.Value

Next prp

End Sub


Nz Function

Use the Nz function to return zero, a zero-length string (" "), or another specified value when a Variant is Null. For example, you can use this function to convert a Null value to another value and prevent it from propagating through an expression.

Syntax

Nz(variant[, valueifnull])

The Nz function uses the following arguments.

Argument	Description

variant	A variable of data type Variant.

valueifnull	Optional. A Variant that supplies a value to be returned if the variant argument is Null. This argument enables you to return a value other than zero or a zero-length string.

If the value of variant is Null, the Nz function returns the number zero or a zero-length string, depending on whether the context indicates the value should be a number or a string. If the optional argument valueifnull is included, then the Nz function will return the value specified by that argument if variant is Null.

If the value of variant is not Null, then the Nz function returns the value of variant.

Remarks

The Nz function is useful for expressions that may include Null values. To force an expression to evaluate to a non-Null value even when it contains a Null value, use the Nz function to return a zero, a zero-length string, or a custom return value.

For example, the expression 2 + varX will always return a Null value when the Variant varX is Null. However, 2 + Nz(varX) returns 2.

You can often use the Nz function as an alternative to the IIf function. For example, in the following code, two expressions including the IIf function are necessary to return the desired result. The first expression including the IIf function is used to check the value of a variable and convert it to zero if it is Null.

varTemp = IIf(IsNull(varFreight), 0, varFreight)

varResult = IIf(varTemp > 50, "High", "Low")

In the next example, the Nz function provides the same functionality as the first expression, and the desired result is achieved in one step rather than two.

varResult = IIf(Nz(varFreight) > 50, "High", "Low")

If you supply a value for the optional argument valueifnull, that value will be returned when variant is Null. By including this optional argument, you may be able to avoid using an expression containing the IIf function. For example, the following expression uses the IIf function to return a string if the value of varFreight is Null.

varResult = IIf(IsNull(varFreight), "No Freight Charge", varFreight)

In the next example, the optional argument supplied to the Nz provides the string to be returned if varFreight is Null.

varResult = Nz(varFreight, "No Freight Charge")


Nz Function Example

The following example evaluates a control on a form and returns one of two strings based on the control's value. If the value of the control is Null, the procedure uses the Nz function to convert a Null value to a zero-length string.

Sub CheckValue()

Dim frm As Form, ctl As Control

Dim varResult As Variant

' Return Form variable pointing to Orders form.

Set frm = Forms!Orders

' Return Control variable pointing to ShipRegion.

Set ctl = frm!ShipRegion

' Choose result based on value of control.

varResult = IIf(Nz(ctl.Value) = "", "No value", "Value is " & ctl.Value)

' Display result.

MsgBox varResult

End Sub


RefreshTitleBar Method

The RefreshTitleBar method refreshes the Microsoft Access title bar after the AppTitle or AppIcon property has been set in Visual Basic. For example, you can change the caption in the Microsoft Access title bar to "Contacts Database" by setting the AppTitle property. In order for this change to take effect, you must subsequently use the RefreshTitleBar method.

Syntax

Application.RefreshTitleBar

The RefreshTitleBar method uses the following argument.

Argument	Description

Application	The Application object.

Remarks

The AppTitle and AppIcon properties enable you to customize your application by changing the title and icon that appear in the Microsoft Access title bar. The title bar is not automatically updated after you have set these properties. In order for the change to the title bar to appear, you must use the RefreshTitleBar method.

You can reset the AppTitle and AppIcon properties to their default value by deleting them from the Properties collection of the Database object representing the current database. After you delete these properties, you must use the RefreshTitleBar method to restore the Microsoft Access defaults to the title bar.


RefreshTitleBar Method Example

The following example sets the AppTitle property of the current database and applies the RefreshTitleBar method to update the title bar.

Sub ChangeTitle()

Dim dbs As Database, prp As Property

Const conPropNotFoundError = 3270

On Error GoTo ErrorHandler

' Return Database variable pointing to current database.

Set dbs = CurrentDb

' Change title bar.

dbs.Properties!AppTitle = "Contacts Database"

' Update title bar on screen.

Application.RefreshTitleBar

Exit Sub

ErrorHandler:

If Err.Number = conPropNotFoundError Then

Set prp = dbs.CreateProperty("AppTitle", dbText, "Contacts Database")

dbs.Properties.Append prp

Else

MsgBox "Error: " & Err.Number & vbCrLf & Err.Description

End If

Resume Next

End Sub


Application Object

The Application object refers to the active Microsoft Access application.

Remarks

The Application object contains all Microsoft Access objects and collections, including the Forms collection, the Reports collection, the Screen object, and the DoCmd object.

You can use the Application object to apply methods or property settings to the entire Microsoft Access application. For example, you can use the SetOption method of the Application object to set database options from Visual Basic. The following example shows how you can set the Show Status Bar option.

Application.SetOption "Show Status Bar", True

Microsoft Access is an OLE Automation server. You can manipulate Microsoft Access objects from another application that is an OLE Automation controller. To do this, you use the Application object.

For example, Microsoft Visual Basic is an OLE Automation controller. You can open a Microsoft Access database from Microsoft Visual Basic and work with its objects. From Microsoft Visual Basic, first create a reference to Microsoft Access. Then create a new instance of the Application object and point an object variable to it, as in the following example.

Dim appAccess As Access.Application

Set appAccess = CreateObject("Access.Application.7")

Once you have created a new instance of the Microsoft Access Application object, you can open a database or create a new database, using either the OpenCurrentDatabase method or the NewCurrentDatabase method. You can then set the properties of the Application object and call its methods.

Note   If you are creating an instance of the Microsoft Access Application object from Microsoft Excel, you must declare the object variable as type Object, as in the following example.

Dim appAccess As Object

Set appAccess = CreateObject("Access.Application.7")

You can also manipulate other Microsoft Access objects through the Application object. For example, using the OpenForm method of the Microsoft Access DoCmd object, you can open a Microsoft Access form from Microsoft Excel.

appAccess.DoCmd.OpenForm "OrderForm"

For more information on creating a reference and controlling objects by OLE Automation, see the documentation for the application that is acting as the OLE Automation controller.


Application Object Example

The following example prints some current property settings of the Application object, sets an option, and then quits the application, saving all objects.

Sub ApplicationInformation()

' Print name and type of current object.

Debug.Print Application.CurrentObjectName

Debug.Print Application.CurrentObjectType

' Set Show Hidden Objects option.

Application.SetOption "Show Hidden Objects", True

' Quit Microsoft Access, saving all objects.

Application.Quit acSaveYes

End Sub

The next example shows how to use Microsoft Access as an OLE Automation server. From Microsoft Visual Basic or another application that acts as an OLE Automation controller, create a reference to Microsoft Access by clicking References on the Tools menu. Select the check box next to Microsoft Access For Windows 95. Then enter the following code in a Visual Basic module within that application.

This procedure creates a new instance of the Application object and opens a new database in the Microsoft Access Database window. It then creates a new form in that database.

Note that an instance of Microsoft Access will close when the variable pointing to the Application object goes out of scope. To prevent Microsoft Access from closing when the procedure has finished running, the variable representing the Application object is declared at the module level in the example below.

' Declare object variable in Declarations section of module.

Dim appAccess As Access.Application

Sub NewAccessDB()

' Declare Database variable and Microsoft Access Form variable.

Dim dbs As Database, frm As Access.Form

' Return instance of Application object.

Set appAccess = CreateObject("Access.Application.7")

' Create new database in Microsoft Access window.

appAccess.NewCurrentDatabase("Newdb.mdb")

' Create new Microsoft Access form in Design view.

set frm = appAccess.CreateForm

' Restore form window.

appAccess.DoCmd.Restore

End Sub


Control Object

The Control object represents a control on a form or report.

Remarks

All controls on a form or report belong to the Controls collection for that Form or Report object. When you refer to an individual Control object in the Controls collection, you can refer to the Controls collection either implicitly or explicitly.

Me!NewData	' Implicitly refer to Controls collection.

Me![New Data]	' Use if control name contains space.

Me("NewData")	' Performance slightly slower.

Me(0)	' Refer to control's index in collection.

Me.Controls!NewData	' Explicitly refer to Controls collection.

Me.Controls[New Data]

Me.Controls("NewData")

Me.Controls(0)

Note   You can use the Me keyword to represent a form or report within code only if you're referring to the form or report from code within the form module or report module. If you're referring to a form or report from a standard module or a different form or report's module, you must use the full reference to the form or report.

Each Control object is denoted by a particular intrinsic constant. For example, the intrinsic constant acTextBox is associated with a text box control, and acCommandButton is associated with a command button. To determine the type of an existing control, use the ControlType property. However, you don't need to know the specific type of a control in order to use it in code. You can simply represent it with a variable of data type Control. You can see these constants in the Object Browser by clicking Modules on the Modules/Classes list, and then looking up the constants in the Methods/Properties list.


Control Object, Controls Collection Example

The following example enumerates all controls in the Controls collection of a form called OrderForm and sets certain properties if the control is a text box.

Sub SetTextBoxProperties()

Dim frm As Form, ctl As Control

Set frm = Forms!OrderForm

' Enumerate Controls collection.

For Each ctl In frm.Controls

' Check to see if control is text box.

If ctl.ControlType = acTextBox Then

' Set control properties.

With ctl

.SetFocus

.Enabled = True

.Height = 400

.SpecialEffect = 0

End With

End If

Next ctl

End Sub


Form Object

A Form object refers to a particular Microsoft Access form.

Remarks

A Form object is a member of the Forms collection. Within the Forms collection, individual forms are numbered by an index beginning with zero. You can refer to an individual Form object in the Forms collection either by referring to the form by name, or by referring to its index within the collection. If the form name includes a space, the name must be surrounded by brackets.

Syntax	Example

Forms!formname	Forms!OrderForm

Forms![form name]	Forms![Order Form]

Forms("formname")	Forms("OrderForm")

Forms(index)	Forms(0)

Each Form object has a Controls collection, which contains all controls on the form. You can refer to a control on a form either by implicitly or explicitly referring to the Controls collection. Your code will be faster if you refer to the Controls collection implicitly. The following examples show two of the ways you might refer to a control named NewData on the form called OrderForm.

Forms!OrderForm!NewData	' Implicit reference.

Forms!OrderForm.Controls!NewData	' Explicit reference.

Many of the properties of a Form object can also be set from a form's property sheet. For information on how to set individual properties, search the online index for those properties.


Forms Collection

The Forms collection contains all of the currently open forms in a Microsoft Access database.

Remarks

Use the Forms collection in Visual Basic or in an expression to refer to forms that are currently open. For example, you can enumerate the Forms collection to set or return the values of properties of individual forms in the collection.

Tip   The For Each...Next statement is useful for enumerating a collection.

You can't add or delete a Form object from the Forms collection.

You can refer to an individual Form object in the Forms collection either by referring to the form by name, or by referring to its index within the collection.

The Forms collection is indexed beginning with zero. If you refer to a form by its index, the first form is Forms(0), the second form is Forms(1), and so on.

Note   To list all forms in the database, whether open or closed, enumerate the Documents collection of the Forms Container object. You can then use the Name property of each individual Document object to return the name of a form.


Form Object, Forms Collection Example

The following example creates a new form and sets certain properties.

Sub NewForm()

Dim frm As Form

' Create new form.

Set frm = CreateForm

' Set form properties.

With frm

.RecordSource = "Products"

.Caption = "Products Form"

.ScrollBars = 0

.NavigationButtons = True

End With

' Restore form.

DoCmd.Restore

End Sub

The next example enumerates the Forms collection and prints the name of each form in the Forms collection. It then enumerates the Controls collection of each form and prints the name of each control on the form.

Sub AllOpenForms()

Dim frm As Form, ctl As Control

' Enumerate Forms collection.

For Each frm In Forms

' Print name of form.

Debug.Print frm.Name

' Enumerate Controls collection of each form.

For Each ctl In frm.Controls

' Print name of each control.

Debug.Print ">>>"; ctl.Name

Next ctl

Next frm

End Sub

The following example uses the Forms collection in an expression. If you have a form OrderForm with a control ShipCountry, you can use the IIf function to return a value based on the current value of the control. If the value of ShipCountry is Null, the expression returns a zero-length string; otherwise, it returns the field's contents. Enter the following expression in the ControlSource property of a text box on a form.

= IIf(IsNull(Forms![Orders]![ShipCountry]), "", Forms![Orders]![ShipCountry])


Report Object

A Report object refers to a particular Microsoft Access report.

Remarks

A Report object is a member of the Reports collection. Within the Reports collection, individual reports are numbered by an index beginning with zero. You can refer to an individual Report object in the Reports collection either by referring to the report by name, or by referring to its index within the collection. If the report name includes a space, the name must be surrounded by brackets.

Syntax	Example

Reports!reportname	Reports!OrderReport

Reports![report name]	Reports![Order Report]

Reports("reportname")	Reports("OrderReport")

Reports(index)	Reports(0)

Each Report object has a Controls collection, which contains all controls on the report. You can refer to a control on a report either by implicitly or explicitly referring to the Controls collection. Your code will be faster if you refer to the Controls collection implicitly. The following examples show two of the ways you might refer to a NewData control on a report called OrderReport.

Reports!OrderReport!NewData	   ' Implicit reference.

Reports!OrderReport.Controls!NewData	   ' Explicit reference.

Many of the properties of a Report object can also be set from a report's property sheet. For information on how to set individual properties, search the online index for those properties.

You can't add or delete a Report object from the Reports collection.


Reports Collection

The Reports collection contains all of the currently open reports in a Microsoft Access database.

Remarks

You can use the Reports collection in Visual Basic or in an expression to refer to reports that are currently open. For example, you can enumerate the Reports collection to set or return the values of properties of individual reports in the collection.

Tip   The For Each...Next statement is useful for enumerating a collection.

You can't add or delete a Report object from the Reports collection.

You can refer to an individual Report object in the Reports collection either by referring to the report by name, or by referring to its index within the collection.

The Reports collection is indexed beginning with zero. If you refer to a report by its index, the first report is Reports(0), the second report is Reports(1), and so on.

Note   To list all reports in the database, whether open or closed, enumerate the Documents collection of the Reports Container object. You can then use the Name property of each individual Document object to return the name of a report.


Report Object, Reports Collection Example

The following example creates a new report and sets certain properties.

Sub NewReport()

Dim rpt As Report

' Return variable of data type Report pointing to new Report object.

Set rpt = CreateReport

' Set properties for new report.

rpt.RecordSource = "Products"

rpt.Caption = "Products Report"

' Restore new report.

DoCmd.Restore

End Sub

The next example enumerates the Reports collection and prints the name of each report in the Reports collection. It then enumerates the Controls collection of each report and prints the name of each control on the report.

Sub AllOpenReports()

Dim rpt As Report, ctl As Control

' Enumerate Reports collection.

For Each rpt In Reports

' Print name of report.

Debug.Print rpt.Name

' Enumerate Controls collection of each report.

For Each ctl In rpt.Controls

' Print name of each control.

Debug.Print ">>>"; ctl.Name

Next ctl

Next rpt

End Sub


Screen Object

The Screen object refers to the particular form, report, or control that currently has the focus.

Remarks

You can use the Screen object together with its properties to refer to a particular form, report, or control that has the focus. For example, you can use the Screen object with the ActiveForm property to refer to the form in the active window without knowing the form's name. The following example displays the name of the form in the active window.

MsgBox Screen.ActiveForm.Name

Referring to the Screen object doesn't make a form, report, or control active. To make a form, report, or control active, you must use the SelectObject method of the DoCmd object.

If you refer to the Screen object when there is no active form, report, or control, Microsoft Access returns a run-time error. For example, if a standard module is in the active window, the code in the example above would return an error.


Screen Object Example

The following example uses the Screen object to print the name of the form in the active window and of the active control on that form.

Sub ActiveObjects()

Dim frm As Form, ctl As Control

' Return Form object pointing to active form.

Set frm = Screen.ActiveForm

MsgBox frm.Name & " is the active form."

' Return Control object pointing to active control.

Set ctl = Screen.ActiveControl

MsgBox ctl.Name & " is the active control on this form."

End Sub


BorderColor Property

You can use the BorderColor property to specify the color of a control's border.

Setting

The BorderColor property setting is a numeric expression that corresponds to the color you want to use for a control's border.

You can use the Color Builder to set this property by clicking the Build button to the right of the property in the property sheet. Using the Color Builder enables you to define custom border colors for controls.

You can also set this property using the Formatting toolbar, a macro, or Visual Basic.

You can set the default for this property using a control's default control style.

Remarks

A control's border color is visible only when its SpecialEffect property is set to Flat or Shadowed. If the SpecialEffect property is set to something other than Flat or Shadowed, setting the BorderColor property changes the SpecialEffect property setting to Flat.


BorderColor, BackColor, ForeColor Properties Example

The following example uses the RGB function to set the BorderColor, BackColor, and ForeColor properties depending on the value of the txtPastDue text box. You can also use the QBColor function to set these properties. Putting the following code in the Form_Current( ) event sets the control display characteristics as soon as the user opens a form or moves to a new record.

Sub Form_Current()

Dim curAmntDue As Currency, lngBlack As Long
Dim lngRed As Long, lngYellow As Long, lngWhite As Long
If Not IsNull(Me!txtPastDue.Value) Then
curAmntDue =Me!txtPastDue.Value
Else
Exit Sub
End If
lngRed = RGB(255, 0, 0)
lngBlack = RGB(0, 0, 0)
lngYellow = RGB(255, 255, 0)
lngWhite = RGB(255, 255, 255)
If curAmntDue > 100 Then
Me!txtPastDue.BorderColor = lngRed
Me!txtPastDue.ForeColor = lngRed
Me!txtPastDue.BackColor = lngYellow
Else
Me!txtPastDue.BorderColor = lngBlack
Me!txtPastDue.ForeColor = lngBlack
Me!txtPastDue.BackColor = lngWhite
End If
End Sub


BorderStyle Property

Forms [image] You can use the BorderStyle property to specify the type of border and border elements (title bar, Control menu, Minimize and Maximize buttons) to use for the form. You typically use different border styles for normal forms, pop-up forms, and custom dialog boxes.

Controls [image] You can use the BorderStyle property to specify how a control's border appears.

Setting

For forms, the BorderStyle property uses the following settings.

Setting	Description	Visual Basic
None	The form has no border or related border elements.	0
Thin	The form has a thin border and can include any of the border elements. The form isn't resizable (the Size command on the Control menu isn't available). You often use this setting for pop-up forms. (If you want a form to remain on top of all Microsoft Access windows, you must also set its PopUp property to Yes.)	1
Sizable	(Default) The form has the default border for Microsoft Access forms, can include any of the border elements, and can be resized. You often use this setting for normal Microsoft Access forms.	2
Dialog	The form has a thick border and can include only a title bar and a Control menu. The form can't be maximized, minimized, or resized (the Maximize, Minimize, and Size commands aren't available on the Control menu). You often use this setting for custom dialog boxes. (If you want a form to be modal, however, you must also set its Modal property to Yes. If you want it to be a modal pop-up form, which dialog boxes typically are, you must set both its PopUp and Modal properties to Yes.)	3
You can set the BorderStyle property only in form Design view using the form's property sheet, a macro, or Visual Basic.

For controls, the BorderStyle property uses the following settings.

Setting	Description	Visual Basic
Transparent	(Default only for label, graph, and subreport) Transparent	0
Solid	(Default) Solid line	1
Dashes	Dashed line	2
Short Dashes	Dashed line with short dashes	3
Dots	Dotted line	4
Sparse Dots	Dotted line with dots spaced far apart	5
Dash Dot	Line with a dash-dot combination	6
Dash Dot Dot	Line with a dash-dot-dot combination	7
You can set the BorderStyle property using the control's property sheet, the Formatting toolbar, a macro, or Visual Basic.

You can also set this property using the controls default control style.

A control's border style is visible only when its SpecialEffect property is set to Flat or Shadowed. If the SpecialEffect property is set to something other than Flat or Shadowed, setting the BorderStyle property changes the SpecialEffect property setting to Flat.

Remarks

For a form, the BorderStyle property establishes the characteristics that visually identify the form as a normal form, a pop-up form, or a custom dialog box. You may also set the Modal and PopUp properties to further define the form's characteristics.

You may also want to set the form's ControlBox, MinMaxButtons, ScrollBars, NavigationButtons, and RecordSelectors properties. These properties interact in the following ways:

If the BorderStyle property is set to None or Dialog, the form doesn't have Maximize or Minimize buttons, regardless of its MinMaxButtons property setting.

If the BorderStyle property is set to None, the form doesn't have a Control menu, regardless of its ControlBox property setting.

If the PopUp property is set to No, the BorderStyle property normally wouldn't be set to Dialog. If you set the PopUp property to No and the BorderStyle property to Dialog, the form doesn't have Maximize and Minimize buttons and can't be resized, but it does have a thin border. If the PopUp property is set to Yes, the BorderStyle property can be any of the four settings.

The BorderStyle property setting doesn't affect the display of the scroll bars, navigation buttons, the record number box, or record selectors.

If you open the form in Form view and then switch to another view, the BorderStyle property setting will be in effect in the other view.

If you set the BorderStyle property of a pop-up form to None, you won't be able to close the form unless you put a Close button on it that runs a macro containing the Close action or an event procedure that uses the Close method.

Pop-up forms are typically fixed in size, but you can make a pop-up form sizable by setting its PopUp property to Yes and its BorderStyle property to Sizable.

You can also use the Dialog setting of the Window Mode argument of the OpenForm action to open a form with its Modal and PopUp properties set to Yes.


ForeColor Property

You can use the ForeColor property to specify the color for text in a control. You can use this property for controls on forms to make them easy to read or to convey a special meaning. For example, you can change the color of the text in the UnitsInStock control when its value falls below the reorder level.

You can use this property on reports to create special visual effects when you print with a color printer. When used on a report, this property specifies the printing and drawing color for the Print, Line, and Circle methods.

Setting

The ForeColor property contains a numeric expression that represents the value of the text color in the control.

For reports, you can set the ForeColor property only in a macro or an event procedure specified in a section's OnPrint event property setting.

For controls, set this property using the Formatting toolbar or the Color Builder.

You can also set this property using the controls default control style.


Picture Property

You can use the Picture property to specify a bitmap to be displayed on a form, report, command button, image frame, or toggle button. Buttons can display either a caption or a picture.

Setting

The Picture property contains the path and filename of a bitmap to be displayed on command button, image frame, or toggle button or as a background picture on a form or report.

You can also use the Picture Builder to select a bitmap by clicking the Build button to the right of the Picture property in the property sheet. If the PictureType property is set to Embedded, the bitmap is stored with the object.

The default setting is "(none)". After the bitmap is loaded into the object, the property setting displays "(bitmap)". If you delete "(bitmap)" from the property setting, the picture is deleted from the object and the property setting is again "(none)".

You can set this property in the property sheet, a macro, or Visual Basic.

In Visual Basic, you can set this property using a string expression that includes the path and the name of the bitmap, as in the following example.

btnShowLogo.Picture = "c:\Windows\Winlogo.bmp"

Remarks

You can create custom bitmaps using Microsoft Paintbrush or another application that creates bitmap files. A bitmap file must have a .bmp, .ico, or .dib extension.

Buttons can display either a caption or a picture. If you assign both to a button, the picture will be visible, the caption will not. If the picture is deleted, the caption reappears. Microsoft Access displays the picture centered on the button and clipped, if the picture is larger than the button.

Tip   To create a command button or toggle button with a caption and a picture, you could include the desired caption as part of the bitmap and assign the bitmap to the Picture property of the control.


Visible Property (Microsoft Access)

You can use the Visible property to show or hide a form, report, form or report section, or control. This may be useful if you want to maintain access to information on a form without it being visible. For example, you could use the value of a control on a hidden form as the criteria for a query.

Setting

The Visible property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The object is visible.	True (-1)
No	The object is not visible.	False (0)
You can set this property using the object's property sheet (for sections and all controls except page breaks), a macro, or Visual Basic.

For forms and reports you must set this property using a macro or Visual Basic.

For controls, you can set this property using the default control style.

Remarks

The Visible property has no effect on a column in Datasheet view. To specify whether a column is visible in Datasheet view, you use the ColumnHidden property.

To hide an object when printing, you use the DisplayWhen property.

You can use the Visible property to hide a control on a form by including the property in a macro that runs when the Current event occurs. For example, you can show or hide a congratulatory message next to a salesperson's monthly sales total in a sales report, depending on the sales total.

Note   There is also a Visible property of the Application object that can be set to cause the application to be invisible. This property can only be set using Visual Basic.


ActiveDatasheet Property

You can use the ActiveDatasheet property together with the Screen object to identify or refer to the Datasheet that has the focus.

Setting

The ActiveDatasheet property setting contains the datasheet object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveDatasheet property to refer to an active datasheet together with one of its properties or methods. For example, the following code uses the ActiveDatasheet property to reference the top row of the selection in the active datasheet.

TopRow = Screen.ActiveDatasheet.SelTop


ActiveDatasheet Property Example

The following example uses the ActiveDatasheet property to identify the datasheet cell with the focus, or if more than one cell is selected, the location of the first row and column in the selection.

Sub GetSelection()

Dim obj As Object

Dim lngFirstRow As Long, lngFirstColumn As Long

Const conNoActiveDatasheet = 2484

On Error GoTo GetSelection_Err

Set obj = Screen.ActiveDatasheet

lngFirstRow = obj.SelTop

lngFirstColumn = obj.SelLeft

MsgBox "The first item in this selection is located at " _

& "Row " & lngFirstRow & ", Column " & lngFirstColumn

GetSelection_Bye:

Exit Sub

GetSelection_Err:

If Err = conNoActiveDatasheet Then

Resume GetSelection_Bye

End If

End Sub


AutoExpand Property

You can use the AutoExpand property to specify whether Microsoft Access automatically fills the text box portion of a combo box with a value that matches the characters as you type in the combo box. This lets you quickly enter an existing value in a combo box without displaying the list box portion of the combo box.

Setting

The AutoExpand property has the following settings.

Setting	Description	Visual Basic
Yes	(Default) Microsoft Access fills in the combo box from the list with the first value matching the first character that you type. As you type additional characters, Microsoft Access changes the value displayed to match all the characters typed.	True (-1)
No	You must select a value from the list or type the entire value.	False (0)
You can set the AutoExpand property using the combo box's property sheet, a macro, or Visual Basic.

Remarks

When you enter characters in the text box portion of a combo box, Microsoft Access searches the values in the list to find those that match the characters you have typed. If the AutoExpand property is set to Yes, Microsoft Access automatically displays the first underlying value that matches the characters entered so far.


ListCount Property

You can use the ListCount property to determine the number of rows in a list box or the list box portion of a combo box.

Setting

The ListCount property holds the number of rows in the list box or the list box portion of the combo box. The value of the ListCount property is read-only and can't be set by the user.

This property is available only in Visual Basic. You can read this property only in Form view and Datasheet view.

Remarks

You can use the ListCount property with the ListRows property to specify how many rows you want to display in the list box portion of a combo box.


ListCount, ListRows Properties Example

This example uses the ListCount property to find the number of rows in the list box portion of the CustomerList combo box on a Customers form. It then sets the ListRows property to display a specified number of rows in the list.

Sub SizeCustomerList()

Dim ListControl As Control

Set ListControl = Forms![Customers]![CustomerList]

If ListControl.ListCount < 8 Then

ListControl.ListRows = ListControl.ListCount

Else

ListControl.ListRows = 8

End If

End Sub


ListIndex Property

You can use the ListIndex property to determine which item is selected in a list box or combo box.

Setting

The ListIndex property is an integer from 0 to the total number of items in a list box or combo box. Microsoft Access sets the ListIndex property value when an item is selected in a list box or list box portion of a combo box. The ListIndex property value of the first item in a list is 0, the value of the second item is 1, and so on.

This property is available only in Visual Basic. You can read this property in Form view and Datasheet view.

Remarks

The ListIndex property value is also available by setting the BoundColumn property to 0 for a combo box or list box. If the BoundColumn property is set to 0, the underlying table field to which the combo box or list box is bound will contain the same list index value as the ListIndex property.

List boxes also have a MultiSelect property that allows the user to select multiple items from the control. When multiple selections are made in a list box, you can determine which items are selected using the Selected property of the control. The Selected property is an array of values from 0 to the ListCount property value minus one. For each item in the list box the Selected property will be True (-1) if the item is selected and False (0) if it is not selected.


ListRows Property

You can use the ListRows property to set the maximum number of rows to display in the list box portion of a combo box.

Setting

The ListRows property holds an integer that indicates the maximum number of rows to display. The default setting is 8.

You can set this property using the combo box's property sheet, a macro, Visual Basic, or the Combo Box Wizard.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box.

Note   Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, use a numeric expression to set the value of this property.

You can also set this property using a combo box's default control style.

Remarks

If the actual number of rows exceeds the number specified by the ListRows property setting, a vertical scroll bar appears in the list box portion of the combo box.


ListWidth Property

You can use the ListWidth property to set the width of the list box portion of a combo box.

Setting

The ListWidth property holds the width, in the current unit of measurement, of the list box portion of a combo box. To use a unit other than the default, include a measurement indicator, such as cm or in. The default setting (Auto) makes the list box portion of the combo box the same width as the combo box.

You can set the ListWidth property using the property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box.

Note   Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, use a numeric expression to set the value of this property. The default unit of measurement in Visual Basic is twips.

You can also set this property using a combo box's default control style.

Remarks

The list portion of the combo box can be wider than the combo box but can't be narrower.

If you want to display a multiple-column list, enter a value that will make the list box wide enough to fit all the columns.

Tip   When designing combo boxes, be sure to leave enough space to display your data and for Microsoft Access to insert a vertical scroll bar.


Text Property

You can use the Text property to set or return the text contained in a text box or the text box portion of a combo box.

Setting

The Text property holds the text you want to display in the control.

You can set this property using only a macro or Visual Basic.

Remarks

To set or return a control's Text property, the control must have the focus (to move the focus to a control, you can use the SetFocus method or GoToControl action).


Text Property Example

This example uses the Text property to retrieve the text box portion of a combo box and then takes an action depending on the user's selection. The Text property setting for the combo box is assigned to the global variable GetText after a user makes a selection in the combo box.

Dim GetText As Variant	 ' Goes in Declarations section of code module.

Sub Combo1_AfterUpdate()

GetText = Me!Combo1.Text

End Sub

The Click event procedure for the DoThis command button contains the code that determines the selection and takes appropriate action.

Sub DoThis_Click()

Select Case GetText

Case "ComboItem1"	 ' Execute if first combo item is selected.

.

.

.

Case "ComboItem2"	 ' Execute if second combo item is selected.

.

.

.

Case "ComboItem3"	 ' Execute if third combo item is selected.

.

.

.

End Select

End Sub


OldValue Property

You can use the OldValue property to determine the unedited value of a bound control.

Setting

The OldValue property contains the unedited data from a bound control and is read-only in all views.

You can access this property only in a macro or Visual Basic.

Thie OldValue property can be assigned to a variable using the following syntax.

OriginalValue = Forms!Customers!AmountPaid.OldValue

Remarks

Microsoft Access uses the OldValue property to retrieve the value of a control as it exists in the underlying record. When you edit a bound control on a form, your changes aren't saved until you move to another record. The OldValue property contains the unedited version of the underlying data.

You can provide your own undo capability by assigning the OldValue property setting to a control. The following example shows how you can restore the unedited contents of the control Date.

Forms!Orders!Date = Forms!Orders!Date.OldValue

If the control hasn't been edited, this example has no effect. When you move to another record, the database is updated, so the current value and the OldValue property will be the same.

The OldValue property setting has the same data type as the field to which the control is bound.


OldValue Property Example

The following example checks to determine if new data entered in a field is within 10 percent of the value of the original data. If the change is greater than 10 percent, the OldValue property is used to restore the original value.

Sub Validate_Field()

Dim curNewValue As Currency, curOriginalValue As Currency

Dim curChange As Currency, strMsg As String

curNewValue = Forms!Employees!RaiseAmount

curOriginalValue = Forms!Employees!RaiseAmount.OldValue

curChange = Abs(curNewValue - curOriginalValue)

If curChange > (curOriginalValue * .1) Then

strMsg = "Change is more than 10 percent of original."

strMsg = strMsg & vbCrLf & "Restoring original value."

MsgBox strMsg, vbExclamation, "Invalid change"

Forms!Employees!RaiseAmount = curOriginalValue

End If

End Sub


SelLength, SelStart, SelText Properties

You can use these properties for tasks such as positioning the insertion point, establishing an insertion range, selecting parts of strings in a control, and deleting text.

SelLength [image] You can use this property to specify or determine the number of characters selected in a text box control or the text box portion of a combo box.

SelStart [image] You can use this property to specify or determine the starting point of the selected text or the position of the insertion point if no text is selected.

SelText [image] You can use this property to specify or determine the string containing the selected text or a zero-length string ("") if no characters are selected.

Setting

SelLength, SelStart [image] An integer in the range 0 to the total number of characters in the control or text box portion of the combo box.

SelText [image] A string expression that equal to the text selected in the control.

You can set the SelLength and SelStart properties using only a macro or Visual Basic. The SelText property is read-only.

Remarks

To set or return these properties for a control, the control must have the focus (to move the focus to a control, you can use the SetFocus method).

Setting the SelLength property to a number less than 0 produces a run-time error.

Setting the SelStart property to a number greater than the number of characters in the control sets the property to the existing text length.

Changing the SelStart property cancels the selection, places an insertion point in the text, and sets the SelLength property to 0.


SelLength, SelStart, SelText Properties Example

The following example uses two event procedures to search for text specified by a user. The text to search through is set in the form's Load event procedure. The Click event procedure for the Find button (which the user chooses to start the search) prompts the user for the text to search for and selects the text in the text box if the search is successful.

Sub Form_Load()

Dim ctlTextToSearch As Control

Set ctlTextToSearch = Forms![Form1]![TextBox1]

ctlTextToSearch.SetFocus	  ' Move focus to text box.

ctlTextToSearch.Text = "This company places large orders twice a year for"

ctlTextToSearch.Text = ctlTextToSearch.Text & " garlic, oregano, chilies and cumin."

End Sub

Sub Find_Click()

Dim strSearch As String, intWhere As Integer

Dim ctlTextToSearch As Control

' Get search string from user.

Set ctlTextToSearch = Forms![Form1]![TextBox1]

' Move focus to text box.

ctlTextToSearch.SetFocus

strSearch = InputBox ("Enter text to be found:")

' Find string in text.

intWhere = InStr (ctlTextToSearch.Text, strSearch)

If intWhere Then	  ' If found.

ctlTextToSearch.SelStart = intWhere - 1	  ' Set SelStart.

ctlTextToSearch.SelLength = Len(strSearch)	  ' Set SelLength.

Else

MsgBox "String not found."	  ' Notify user.

End If

End Sub


Event Properties

Event properties cause a macro or the associated Visual Basic event procedure to run when a particular event occurs. For example, if you enter the name of a macro in a command button's OnClick property, that macro runs when the command button is clicked. For a complete list of event properties, see Events and Event Properties Reference.

Setting

To run a macro, enter the name of the macro. You can choose an existing macro in the list. If the macro is in a macro group, it will be listed under the macro group name, as macrogroupname.macroname.

To run the event procedure associated with the event, select [Event Procedure] in the list.

Note   Although using an event procedure is the recommended method for running Visual Basic code in response to an event, you can also run a user-defined function when an event occurs. To run a user-defined function, place an equal sign (=) before the function name and parentheses after it, as in =functionname( ).

You can set event properties in the property sheet for an object or in a macro or Visual Basic. Note that you can't set any event properties while you're formatting or printing a form or report.

Tip   You can use builders to help you set an event property. Click the Build button to the right of the property box, or click the right mouse button when the pointer is over the property box and then click Build on the shortcut menu. In the Choose Builder dialog box, select:

The Macro Builder to create and specify a macro for this event property. You can also use the Macro Builder to edit a macro already specified by the property.

The Code Builder to create and specify an event procedure for this event property. You can also use the Code Builder to edit an event procedure already specified by the property.

The Expression Builder to choose and specify a user-defined function for this event property.

In Visual Basic, set the property to a string expression.

To run this	Use this syntax	Example
Macro	"macroname"	Button1.OnClick = "MyMacro"
Event procedure	"[Event Procedure]"	Button1.OnClick = "[Event Procedure]"
User-defined function	"=functionname( )"	Button1.OnClick = "=MyFunction()"


Event Properties - Visual Basic Example
Event Properties — Visual Basic Example

The following example shows how you can use the value entered in the Country control to determine which of two different macros to run when you click the Print Country Report button.

Sub Country_AfterUpdate()

If Country = "Canada" Then

[Print Country Report].OnClick = "PrintCanadaReport"

ElseIf Country = "USA" Then

[Print Country Report].OnClick = "PrintUSAReport"

End If

End Sub


Event Properties and Objects They Apply To

Event Property	Applies To

AfterDelConfirm	Forms.

AfterInsert	Forms.

AfterUpdate*	Forms. Controls (bound object frame, check box, combo box, list box, option button, option group, text box, toggle button) on a form.

BeforeDelConfirm	Forms.

BeforeInsert	Forms.

BeforeUpdate*	Forms. Controls (bound object frame, check box, combo box, list box, option button, option group, text box, toggle button) on a form.

OnActivate	Forms and reports.

OnApplyFilter	Forms.

OnChange	Controls (combo box, text box) on a form.

OnClick*	Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.

OnClose	Forms and reports.

OnCurrent	Forms.

OnDblClick*	Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.

OnDeactivate	Forms and reports.

OnDelete	Forms.

OnEnter*	Controls (bound object frame, chart, check box, combo box, command button, list box, option button, option group, subform/subreport, text box, toggle button, unbound object frame) on a form.

OnError	Forms and reports.

OnExit*	Controls (bound object frame, chart, check box, combo box, command button, list box, option button, option group, subform/subreport, text box, toggle button, unbound object frame) on a form.

OnFilter	Forms.

OnFormat	Report sections.

OnGotFocus	Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.

OnKeyDown	Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.

OnKeyPress	Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.

OnKeyUp	Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.

OnLoad	Forms.

OnLostFocus	Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, text box, toggle button, unbound object frame) on a form.

OnMouseDown	Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.

OnMouseMove	Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.

OnMouseUp	Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, label, list box, option button, option group, rectangle, text box, toggle button, unbound object frame) on a form.

OnNoData	Reports.

OnNotInList	Controls (combo box) on a form.

OnOpen	Forms and reports.

OnPage	Reports.

OnPrint	Report sections.

OnResize	Forms.

OnRetreat	Report sections.

OnTimer	Forms.

OnUnload	Forms.

OnUpdated	Controls (bound object frame, unbound object frame) on a form.

* These properties don't apply to check boxes, option buttons, or toggle buttons in an option group. They apply only to the option group itself.


AllowFilters Property

You can use the AllowFilters property to specify whether records can be filtered.

Settings

The AllowFilters property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) Records can be filtered.	True (-1)
No	Records can't be filtered.	False (0)
You can set this property using the form's property sheet, a macro, or Visual Basic.

Remarks

Filters are commonly used to view a temporary subset of the records in a database. When you use a filter, you apply criteria to display only records that meet specific conditions. In an Employees table, for example, you can use a filter to display only records of employees with over 5 years of service. You can also use a filter to restrict access to records containing sensitive information, such as financial or medical data.

When the AllowFilters property is set to No, all of the filter options on the Records menu and the shortcut menu are disabled.


AllowFilters Property Example

The following example shows a function that toggles a form's AllowFilters property on and off.

Function ToggleAllowFilters() As Integer

Forms!Customers.AllowFilters = Not Forms!Customers.AllowFilters

End Function


ControlBox Property

You can use the ControlBox property to specify whether a form has a Control menu in Form view.

Setting

The ControlBox property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The form has a Control menu in Form view.	True (-1)
No	The form doesn't have a Control menu in Form view.	False (0)
You can set this property using the form's property sheet, a macro, or Visual Basic.

You can set this property only in form Design view.

Note   Setting the ControlBox property to No removes the Minimize, Maximize, and Close buttons on a form.

Remarks

To display a Control menu on a form, the ControlBox property must be Yes and the form's BorderStyle property must be set to Thin, Sizable, or Dialog.

Even when a form's ControlBox property is set to No, the form always has a Control menu when opened in Design view.

Setting the ControlBox property to No suppresses the Control menu when you open the form in Form view from the Database window, using a macro, or Visual Basic. The Control menu is also suppressed when you switch to another view from Form view.


ControlBox Property Example

The following example sets the ControlBox property on the WarningBox form to False.

Forms!WarningBox.ControlBox = False


DisplayWhen Property

You can use the DisplayWhen property to specify which of a Form's sections or controls you want displayed on screen and in print.

Note   The DisplayWhen property applies only to all controls (except page breaks) on a form.

Setting

The DisplayWhen property uses the following settings.

Setting	Description	Visual Basic
Always	(Default) The object appears in Form view and when printed.	0
Print Only	The object is hidden in Form view but appears when printed.	1
Screen Only	The object appears in Form view but not when printed.	2
You can set this property in the object's property sheet, a macro, or Visual Basic.

For controls, you can set this property using the control's default control style.

Remarks

In many cases certain controls are useful only in Form view. To prevent Microsoft Access from printing these controls, you can set their DisplayWhen property to Screen Only. For example, you might have a command button or instructions on a form that you don't want printed. Or you might have form header and form footer sections that you don't want displayed on screen but that you do want printed. In this case, you should set the DisplayWhen property to Print Only.

Tip   For reports, use the Format and Retreat events to specify an event procedure or macro that sets the Visible property of controls you don't want printed.


LayoutForPrint Property

You can use the LayoutForPrint property to specify whether the form or report uses printer or screen fonts.

Setting

The LayoutForPrint property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default for reports) Use printer fonts.	True (-1)
No	(Default for forms) Use screen fonts.	False (0)
The property can be set only in form Design view and report Design view.

Remarks

When you choose a font in Microsoft Access, you are choosing either a screen font or a printer font, depending on the setting of the LayoutForPrint property. Remember that printer fonts and screen fonts can differ, and characters on screen may not look exactly like those displayed on the printed page.

Tip   If you select a scalable font, such as a TrueType font, the screen and printer characters will look nearly the same.

Screen fonts are the images of letters, numbers, and symbols displayed on the screen. The screen fonts Microsoft Access uses are those that were installed when you installed Windows. If you installed a printer, additional screen fonts may have been installed automatically. You may also have added more screen fonts on your own.

Printer fonts are the letters, numbers, and symbols that are produced when you print a report or a form. The available fonts depend on your printer.

If you set the LayoutForPrint setting to Yes, the Formatting toolbar displays the fonts and point sizes available for your printer.

If you design a form or report on a system with a different printer than the one you will use to print, Microsoft Access displays a message to let you know that the form or report was designed for another kind of printer. If you print the form or report anyway, your printer may substitute different fonts. You can reselect the font for each control to specify the appearance of the form or report.


MinMaxButtons Property

You can use the MinMaxButtons property to specify whether Maximize or Minimize buttons will be available on a form.

Setting

The MinMaxButtons property uses the following settings.

Setting	Description	Visual Basic
None	The form will not have Maximize or Minimize buttons.	0
Min Enabled	Only the Minimize button is available.	1
Max Enabled	Only the Maximize button is available.	2
Both Enabled	(Default) Both the Minimize and Maximize buttons are available.	3
You can set these properties using the form's property sheet, a macro, or Visual Basic.

You can set the MinMaxButtons property only in form Design view.

Remarks

Clicking a form's Maximize button enlarges the form so it fills the Microsoft Access window. Clicking a form's Minimize button reduces the form to an icon at the bottom of the Microsoft Access window.

To display Maximize and Minimize buttons on a form, you must set the form's BorderStyle property to Thin or Sizable and the ControlBox property to Yes. If you set the BorderStyle property to None or Dialog, or if you set the ControlBox property to No, the form won't have Maximize or Minimize buttons, regardless of the MinMaxButtons property setting.

Even when the MinMaxButtons property is set to None, a form always has Maximize and Minimize buttons in Design view.

If a form's MinMaxButtons property is set to None, the Maximize and Minimize commands aren't available on the form's Control menu.


MenuBar Property

You can use the MenuBar property to specify the menu bar macro that will to display a custom menu bar for a database, form, or report.

Setting

Enter the name of the menu bar macro that displays a custom menu bar. If you leave the MenuBar property setting blank, Microsoft Access displays the built-in (default) menu bar or the application’s global menu bar.

You can set this property using the object's property sheet, a macro, or Visual Basic.

In Visual Basic, set this property using a string expression that is the name of the menu bar macro you want to run.

To display the built-in menu bar for a database, form, or report using a macro or Visual Basic, set the property to a zero-length string (" ").

Tip   To create a menu bar macro, you can use the Menu Builder by clicking the Build button in the MenuBar property box of the form or report you want to attach the menu to. The Menu Builder creates and names the menu bar macro and the macro group containing the actions for the menu commands on the menus you create. If you use the Menu Builder to create the menu bar macro and the macro group for the menus on this menu bar, you can also use the Menu Builder to edit this macro and macro group.

Remarks

When you use the MenuBar property with forms and reports, Microsoft Access runs the specified menu bar macro and displays the custom menu bar when the form or report is opened. This menu bar is displayed whenever the form or report has the focus.

The menu bar macro contains AddMenu actions that create the drop-down menus on the custom menu bar. For each drop-down menu, the menu bar macro names the macro group that defines the commands on the menu. If you make changes to the menu bar macro or the macro group that defines the commands on the drop-down menus while the form or report is open, you must close the form or report and reopen it to see the changes in the custom menu bar and its menus.

You can't use any action except AddMenu in a menu bar macro.

When used with the Application object, the MenuBar property enables you to display a custom menu bar throughout the database. However, if you've set the MenuBar property for a form or report in the database, the custom menu bar of the form or report takes precedence over the database's custom menu bar. You can display a different custom menu bar for a specific form or report by setting its MenuBar property to a different menu bar macro. When the form or report has the focus, the custom menu bar for the form or report is displayed; when the form or report loses the focus, the custom menu bar for the database is displayed.

Note   You can switch between a database's custom menu bar and the built-in menu bar by pressing CTRL+F11.


MenuBar Property Example

The following example sets the MenuBar property to a menu bar macro named CustomerMenu.

Forms![Customers].MenuBar = "CustomerMenu"

To display the built-in menu bar for the form or the application global menu, you set the MenuBar property to a zero-length string (" ").

Forms![Customers].MenuBar = ""


Modal Property

You can use the Modal property to specify whether a form opens as a modal form. When a form opens as a modal form, you must close the form before you can move the focus to another object.

Setting

The Modal property uses the following settings.

Setting	Description	Visual Basic
Yes	The form opens as a modal form in Form view.	True (-1)
No	(Default) The form isn't a modal form when it opens.	False (0)
You can set this property using the form's property sheet, a macro, or Visual Basic.

Remarks

When you open a modal form, other windows are disabled until you close it. To disable menus and toolbars in addition to other windows, set both the form's Modal and PopUp properties to Yes.

You can use the BorderStyle property to specify the kind of border for a form. Typically, modal forms have the BorderStyle property set to Dialog.

Tip   You can use the Modal, PopUp and BorderStyle properties to create a custom dialog box. You can set Modal to Yes, PopUp to Yes and BorderStyle to Dialog for custom dialog boxes.

Setting the Modal property to Yes makes the form modal only when you open it in Form view from the Database window or using a macro or Visual Basic. When the form is modal, you can't switch to other views of the form from Form view. You must close the form and reopen it in Design view or Datasheet view.

Note   You can use the Dialog setting of the Window Mode argument of the OpenForm action to open a form with its Modal and PopUp properties set to Yes.


NavigationButtons Property

You can use the NavigationButtons property to specify whether navigation buttons and a record number box are displayed on a form.

Setting

The NavigationButtons property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The form has navigation buttons and a record number box.	True (-1)
No	The form doesn't have navigation buttons or a record number box.	False (0)
You can set this property using the form's property sheet, a macro, or Visual Basic.

Remarks

Navigation buttons provide an efficient way to move to the first, previous, next, or last record. A record number box displays the number of the current record and the total number of records.

If you remove the navigation buttons from a form, you can create custom navigation buttons and add them to the toolbar for the form.


AutoResize Property

You can use the AutoResize property to specify whether a Form window opens automatically sized to display complete records.

Setting

The AutoResize property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The Form window is automatically sized to display a complete record.	True (-1)
No	When opened, the Form window has the last saved size. To save a form window's size, open the form, size the window, save the form by clicking Save on the File menu, and close the form. When you next open the form, it will be the saved window size.	False (0)
You can set this property in the form's property sheet, a macro, or Visual Basic.

This property can be set only in Design view.

Remarks

The Form window resizes only if opened in Form view. If you open the form first in Design view or Datasheet view and then change to Form view, the Form window won't resize.

If a form's AutoResize property is set to No and its AutoCenter property is set to Yes, and if you make any changes in Design view and don't switch to Form view before saving the form, Microsoft Access clips the form on the right and bottom edges the next time you open the form.

If the AutoCenter property is set to No, a Form window opens with its upper-left corner in the same location as when it was closed.


Cancel Property

You can use the Cancel property to specify whether a command button is also the Cancel button on a form.

Setting

The Cancel property has the following settings.

Setting	Description	Visual Basic
Yes	The command button is the Cancel button.	True (-1)
No	(Default) The command button isn't the Cancel button.	False (0)
You can set this property using the command button's property sheet, a macro, or Visual Basic.

Remarks

When a command button's Cancel property setting is Yes and the form is in the active window, the user can choose the command button by pressing ESC, or pressing ENTER when the command button has the focus, or by clicking the command button.

Note   If a text box has the focus when the user presses ESC, any changes made to the data in the text box will be lost, and the original data is restored.

When the Cancel property is set to Yes for one command button, it is automatically set to No for all other command buttons.

Tip   For a form that supports irreversible operations, such as deletions, it's a good idea to make the Cancel button the default command button. To do this, set both the Cancel property and the Default property to Yes.


Default Property

You can use the Default property to specify whether a command button on a form has the focus.

Setting

The Default property uses the following settings.

Setting	Description	Visual Basic
Yes	The command button is the default button.	True (-1)
No	(Default) The command button isn't the default button.	False (0)
You can set this property using the command button's property sheet, a macro, or Visual Basic.

Remarks

When the command button's Default property setting is Yes and the form is in the active window, the user can choose the command button by pressing ENTER (if no other command button has the focus) or by clicking on it.

Only one command button on a form can be the default button. When the Default property is set to Yes for one command button, it is automatically set to No for all other command buttons on the form.

Tip   For a form that supports irreversible operations, such as deletions, it's a good idea to make the Cancel button the default command button. To do this, set both the Default property and the Cancel property to Yes.


DefaultView, ViewsAllowed Properties

You can use these two properties to specify the view a form displays when it opens and whether users can switch to and from Datasheet view and Form view.

DefaultView [image] You can use this property to specify the opening view of a form.

ViewsAllowed [image] You can use this property to specify whether users can switch between Datasheet view and Form view by clicking the Form or Datasheet command on the View menu.

Setting

The DefaultView property uses the following settings.

Setting	Description	Visual Basic
Single Form	(Default) Displays one record at a time.	0
Continuous Forms	Displays multiple records (as many as will fit in the current window), each in its own copy of the detail section of the form.	1
Datasheet	Displays the form fields arranged in rows and columns like a spreadsheet	2
The ViewsAllowed property uses the following settings.

Setting	Description	Visual Basic
Both	(Default) Users can switch between Form view and Datasheet view.	0
Form	Users can't switch to Datasheet view from Form view.	1
Datasheet	Users can't switch to Form view from Datasheet view.	2
Design view is always available (unless permissions are set otherwise).

You can set these properties in the property sheet, a macro, or Visual Basic.

Remarks

The combination of these properties creates the following conditions.

DefaultView	ViewsAllowed	Description
Single, Continuous Forms, or Datasheet	Both	Users can switch between Form view and Datasheet view.
Single or Continuous Forms	Form	Users can't switch from Form view to Datasheet view.
Single or Continuous Forms	Datasheet	Users can switch from Form view to Datasheet view but not back again.
Datasheet	Form	Users can switch from Datasheet view to Form view but not back again.
Datasheet	Datasheet	Users can't switch from Datasheet view to Form view.


GridX, GridY Properties

You can use the GridX and GridY properties to specify the horizontal and vertical divisions of the alignment grid in form Design view or report Design view.

Setting

Enter an integer for the number of subdivisions per unit of measurement. If the measurement system is U.S., the default setting is 24 for the GridX property (horizontal) and 24 for the GridY property (vertical).

You can set this property in the property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property using a numeric expression

Remarks

The GridX and GridY properties provide control over the placement and alignment of objects on a form or report. You can adjust the grid for greater or lesser precision. To see the grid, click Grid on the View menu. If the setting for either the GridX or GridY properties is greater than 24, the grid points disappear from view.


Painting Property

You can use the Painting property to specify whether forms or reports are repainted.

Setting

The Painting property uses the following settings.

Setting	Description

True	(Default) The form or report is repainted.

False	The form or report isn't repainted.

You can set this property using only a macro or Visual Basic.

This property applies only in Form view and is unavailable in other views.

Remarks

The Painting property is similar to the Echo action. However, the Painting property prevents repainting of a single form or report, whereas the Echo action prevents repainting of all open windows in an application.

Setting the Painting property for a form or report to False also prevents all controls (except subform or subreport controls) on a form or report from being repainted. To prevent a subform or subreport control from being repainted, you must set the Painting property for the subform or subreport to False. (Note that you set the Painting property for the subform or subreport, not the subform or subreport control.)


Painting Property Example

The following example uses the Painting property to enable or disable form painting depending on whether the SetPainting variable is set to True or False. If form painting is turned on, Microsoft Access displays the hourglass icon while repainting.

Function EnablePaint(frmName As Form, ByVal SetPainting As Integer) As Integer

frmName.Painting = SetPainting

If SetPainting = False Then	  ' Form painting is turned off.

DoCmd.Hourglass True	  ' Display icon.

Else

DoCmd.Hourglass False	  ' Don't display icon.

End If

End Function


RecordSelectors Property

You can use the RecordSelectors property to specify whether a form displays record selectors in Form view.

Setting

The RecordSelectors property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) Each record has a record selector.	True (-1)
No	No record has a record selector.	False (0)
You can set this property using the form's property sheet, a macro, or Visual Basic.

Remarks

You can use this property to remove record selectors when you create or use a form as a custom dialog box or a palette.

The record selector displays an icon when a record is being edited. When the RecordSelectors property is set to No and the RecordLocks property is set to Edited Record (record locking is pessimistic), there is no visual clue that the record is locked.


ScrollBars Property

You can use the ScrollBars property to specify whether scroll bars appear on a form or in a text box control.

Setting

The ScrollBars property uses the following settings.

Setting	Description	Visual Basic
Neither	(Default for text boxes) No scroll bars appear on the form or text box.	0
Horizontal Only	Horizontal scroll bar appears on the form. Not applicable to text boxes.	1
Vertical Only	Vertical scroll bar appears on the form or text box.	2
Both	(Default for forms) Vertical and horizontal scroll bars appear on the form. Not applicable to text boxes.	3
You can set this property in the form or control's property sheet or using a macro or Visual Basic.

For a text box, you can set this property using the default control style.

Remarks

If the your form is larger than the available display window, you can use the ScrollBars property to allow the user to view the entire form.

You can use the NavigationButtons property to control record navigation.


StatusBarText Property

You can use the StatusBarText property to specify the text that is displayed in the status bar when a control is selected.

Note   The StatusBarText property applies only to controls on a form.

Setting

You set the StatusBarText property using a string expression up to 255 characters long.

You can set this property in the or control's property sheet or using a macro or Visual Basic.

You can also set this property using the control's default control style.

Note   The length of the text you can display in the status bar depends on your computer hardware and video display.

Remarks

You can use the StatusBarText property to provide specific information about a control. For example, when a text box has the focus, a brief instruction can tell the user what kind of data to enter.

If you create a control by dragging a field from the field list, the value in a field's Description property is copied to the StatusBarText property.


CurrentX, CurrentY Properties

You can use the CurrentX and CurrentY properties to specify the horizontal and vertical coordinates for the starting position of the next printing and drawing method on a report. For example, you use these properties to determine where the center point of a circle is drawn on a report section.

Setting

CurrentX [image] A Single data type value used in a numeric expression to set the horizontal coordinate of the next printing drawing method.

CurrentY [image] A Single data type value used in a numeric expression to set the vertical coordinate of the next printing drawing method.

The coordinates are measured from the upper-left corner of the report section that contains the reference to the CurrentX or CurrentY property. The CurrentX property setting is 0 at the section's left edge, and the CurrentY property setting is 0 at its top edge.

You can set the CurrentX and CurrentY properties only in a macro or a Visual Basic event procedure specified by the OnPrint property setting of a report section.

Remarks

Use the ScaleMode property to define the unit of measure, such as points, pixels, characters, inches, millimeters, or centimeters, that the coordinates will be based on.

When you use the following graphics methods, the CurrentX and CurrentY property settings are changed as indicated.

Method	Sets CurrentX, CurrentY to

Circle	The center of the object.

Line	The end point of the line (the x2, y2 coordinates).

Print	The next print position.


DrawMode Property

You can use the DrawMode property to specify how the pen (the color used in drawing) interacts with existing background colors on the report when the Line, Circle, or PSet method is used to draw on a report when printing.

Setting

The DrawMode property uses the following settings.

Setting	Description

1	Black pen.

2	Inverse of setting 15 (NotMergePen).

3	Combination of the colors common to the background color and the inverse of the pen (MaskNotPen).

4	Inverse of setting 13 (NotCopyPen).

5	Combination of the colors common to both the pen and the inverse of the display (MaskPenNot).

6	Inverse of the display color (Invert).

7	Combination of the colors in the pen and in the display color, but not in both (XorPen).

8	Inverse of setting 9 (NotMaskPen).

9	Combination of the colors common to both the pen and the display (MaskPen).

10	Inverse of setting 7 (NotXorPen).

11	No operation [image] output remains unchanged. In effect, this setting turns drawing off (Nop).

12	Combination of the display color and the inverse of the pen color (MergeNotPen).

13	(Default) Color specified by the ForeColor property (CopyPen).

14	Combination of the pen color and the inverse of the display color (MergePenNot).

15	Combination of the pen color and the display color (MergePen).

16	White pen.

The DrawMode property setting is an Integer data type value.

You can set the DrawMode property only in a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

Use this property to produce visual effects when drawing on a report. Microsoft Access compares each pixel in the draw pattern to the corresponding pixel in the existing background to determine how the drawing is displayed on the report. For example, setting 7 uses the Xor operator to combine a draw-pattern pixel with a background pixel.


DrawStyle Property

You can use the DrawStyle property to specify the line style when using the Line and Circle methods to print lines on reports.

Setting

The DrawStyle property uses the following settings.

Setting	Description

0	(Default) Solid line, transparent interior

1	Dash, transparent interior

2	Dot, transparent interior

3	Dash-dot, transparent interior

4	Dash-dot-dot, transparent interior

5	Invisible, transparent interior

6	Invisible line, solid interior

The DrawStyle property setting has an Integer data type value.

You can set this property only in a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

The DrawStyle property produces the results described in the preceding table if the DrawWidth property is set to 1. If the DrawWidth property setting is greater than 1, DrawStyle settings 1 through 4 produce a solid line (the DrawStyle property value isn't changed).


DrawWidth Property

You can use the DrawWidth property to specify the line width for the Line, Circle, and PSet methods.

Setting

You can set the DrawWidth property to an Integer value of 1 through 32,767. This value represents the width of the line in pixels. The default is 1, or 1 pixel wide.

You can set this property only in a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

Increase the value of this property to increase the width of the line. If DrawWidth is greater than 1, DrawStyle property settings 1 through 4 produce a solid line (the DrawStyle property value isn't changed). Setting the DrawWidth property to 1 enables the DrawStyle property to produce the results shown in the setting table of the DrawStyle property.


FillStyle Property

You can use the FillStyle property to specify whether a circle or line drawn by the Circle or Line method is transparent or filled with a pattern.

Setting

The FillStyle property uses the following settings.

Setting	Description

0	Opaque

1	(Default) Transparent

2	Horizontal Line

3	Vertical Line

4	Upward Diagonal

5	Downward Diagonal

6	Cross

7	Diagonal Cross

You can set the FillStyle property only in a macro or a Visual Basic event procedure specified by the OnPrint property setting of a report section.

Remarks

When the FillStyle property is set to 0, a circle or line has the color set by the FillColor property. When the FillStyle property is set to 1, the interior of the circle or line is transparent and has the color of the report behind it.

To use the FillStyle property, the SpecialEffect property must be set to Normal.


ScaleHeight, ScaleWidth Properties

You can use the ScaleHeight and ScaleWidth properties to specify the number of units for the vertical or horizontal measurement of the page when the Circle, Line, PSet, or Print method is used while a report is printed or previewed.

Setting

ScaleHeight [image] A Single data type value used in a numeric expression to set the number of units for the vertical measurement of the page.

ScaleWidth [image] A Single data type value used in a numeric expression to set the number of units for the horizontal measurement of the page.

The default settings are the internal height and width of a report page in twips.

You can set the ScaleHeight and ScaleWidth properties only in a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

You can use the ScaleHeight and ScaleWidth properties to create a custom coordinate scale for drawing or printing. For example, the statement ScaleHeight = 100 defines the internal height of the section as 100 units, or one vertical unit as 1/100 of the height.

Use the ScaleMode property to define a scale based on a standard unit of measurement, such as points, pixels, characters, inches, millimeters, or centimeters.

Setting the ScaleHeight and ScaleWidth properties to positive values makes coordinates increase in value from top to bottom and left to right. Setting them to negative values makes coordinates increase in value from bottom to top and right to left.

Using these properties and the related ScaleLeft and ScaleTop properties, you can set up a full coordinate system with both positive and negative coordinates. All four of these scale properties interact with the ScaleMode property in the following ways:

Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

Setting the ScaleMode property to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0. Also, the CurrentX and CurrentY property settings change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note   The ScaleHeight and ScaleWidth properties aren't the same as the Height and Width properties.


ScaleLeft, ScaleTop Properties

You can use the ScaleLeft and ScaleTop properties in Visual Basic to specify the horizontal or vertical coordinates that describe the location of the left and top edges of a page when the Circle, Line, PSet, or Print method is used while a report is previewed, printed, or its output is saved to a file.

Setting

ScaleLeft [image] A Single data type value used in a numeric expression to set the number of units for the horizontal coordinate of the left edge of a page. The default setting is 0.

ScaleTop [image] A Single data type value used in a numeric expression to set the number of units for the vertical coordinate of the top edge of a page. The default setting is 0.

You can set the ScaleLeft and ScaleTop properties only in a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

Using these properties and the related ScaleHeight and ScaleWidth properties, you can set up a full coordinate system with both positive and negative coordinates. These four scale properties interact with the ScaleMode property in the following ways:

Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

Setting the ScaleMode property to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0. Also, the CurrentX and CurrentY property settings change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note   The ScaleLeft and ScaleTop properties aren't the same as the Left and Top properties.


ScaleMode Property

You can use the ScaleMode property in Visual Basic to specify the unit of measurement for coordinates on a page when the Circle, Line, PSet, or Print method is used while a report is previewed or printed.

Setting

The ScaleMode property uses the following settings.

Setting	Description

0	Indicates that one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties are set to custom values

1	(Default) Twip

2	Point

3	Pixel

4	Character (horizontal = 120 twips per unit; vertical = 240 twips per unit)

5	Inch

6	Millimeter

7	Centimeter

The property setting has an Integer data type value.

You can set the ScaleMode property only in a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

Using the related ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties, you can create a custom coordinate system with both positive and negative coordinates. These four Scale properties interact with the ScaleMode property in the following ways:

Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

Setting the ScaleMode property to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0. The CurrentX and CurrentY property settings change to reflect the new coordinates of the current point.


ImageHeight Property

You can use the ImageHeight property in Visual Basic to determine the height in twips of the picture in an image control.

Setting

The ImageHeight property is an Integer value equal to the height of a picture in twips.

This property is read-only in all views.

Remarks

You can use the ImageHeight property together with the ImageWidth property to determine the size of a picture in an image control. You could then use this information to change the image control's Height and Width properties to match the size of the picture displayed.


ImageHeight, ImageWidth Properties Example

The following example prompts the user to enter the name of a bitmap and then assigns that bitmap to the Picture property of the Image1 image control. The ImageHeight and ImageWidth properties are used to resize the image control to fit the size of the bitmap.

Sub GetNewPicture(frm As Form)

Dim ctlImage As Control

Set ctlImage = frm!Image1

ctlImage.Picture = InputBox("Enter path and filename for new bitmap")

ctlImage.Height = ctlImage.ImageHeight

ctlImage.Width = ctlImage.ImageWidth

End Sub


ImageWidth Property

You can use the ImageWidth property in Visual Basic to determine the width in twips of a picture in an image control.

Setting

The ImageWidth property is an Integer value equal to the width of a picture in twips.

This property is read-only in all views.

Remarks

You can use the ImageWidth property together with the ImageHeight property to determine the size of a picture in an image control. You could then use this information to change the image control's Height and Width properties to match the size of the picture displayed.


Cycle Property

You can use the Cycle property to specify what happens when you press the TAB key when the focus is in the last control on a bound form.

Setting

The Cycle property uses the following settings.

Setting	Description	Visual Basic
All Records	(Default) Pressing the TAB key from the last control on a form moves the focus to the first field in the next record in the underlying source of data.	0
Current Record	Pressing the TAB key from the last control on a form moves the focus to the first control in the tab order on the form in the same record.	1
Current Page	Pressing the TAB key from the last control on a page moves the focus back to the first control in the tab order on the page.	2
You can set the Cycle property in the form's property sheet, a macro, or using Visual Basic.

You can set the Cycle property in any view.

Remarks

When you press the TAB key on a form the focus moves through the controls on the form according to the control's place in the tab order.

You can set the Cycle property to All Records for forms designed for data entry. This allows the user to move to a new record by pressing the TAB key.


KeyPreview Property

You can use the KeyPreview property to specify whether form keyboard events are invoked before control keyboard events.

Note   The keyboard events are KeyDown, KeyUp, and KeyPress.

Setting

The KeyPreview property uses the following settings.

Setting	Description	Visual Basic
Yes	The form receives keyboard events first, then the active control receives keyboard events.	True (-1)
No	(Default) Only the active control receives keyboard events.	False (0)
You can set the KeyPreview property in the form's property sheet, a macro, or using Visual Basic.

You can set the KeyPreview property in any view.

Remarks

You can use the KeyPreview property to create a keyboard-handling procedure for a form. For example, when an application uses function keys, setting the KeyPreview property to True allows you to process keystrokes at the form level rather than writing code for each control that might receive keystroke events.

To handle keyboard events only at the form level and prevent controls from receiving keyboard events, set KeyAscii to 0 in the form's KeyPress event, and set KeyCode to 0 in the form's KeyDown and KeyUp events.

If a form has no visible or enabled controls, it automatically receives all keyboard events.


KeyPreview Property Example

In the following example the KeyPreview property is set to True in the form's load event. This causes the form to receive keyboard events before they are received by any control. The form KeyDown event then examines the KeyCode value to determine if the F2, F3, or F4 keys were pushed.

Private Sub Form_Load()

Me.KeyPreview = True

End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

Const conKey_F2 = &H71	' F2 Key constant

Const conKey_F3 = &H72	' F3 Key constant

Const conKey_F4 = &H73	' F4 Key constant

Select Case KeyCode

Case conKey_F2

' Process F2 key events

Case conKey_F3

' Process F3 key events

Case conKey_F4

' Process F4 key events

Case Else

End Select

End Sub


ShortcutMenuBar Property

You can use the ShortcutMenuBar property to specify the menu bar macro to use to display a shortcut menu when you right click on a form or control.

Setting

You set the ShortcutMenuBar property using the name of a menu bar macro.

You can set the ShortcutMenuBar property in the form or control's property sheet, a macro, or using Visual Basic.

For controls on forms, you can also set this property using the control's default control style.

In Visual Basic, set this property using a string expression that is the name of the menu bar macro you want to run.

Tip   To create a menu bar macro, you can use the Menu Builder by clicking the Build button in the ShortcutMenuBar property box of the form or control you want to attach the menu to. The Menu Builder creates and names the menu bar macro and the macro group containing the actions for the menu commands on the menus you create.

Remarks

The macro specified in the ShortcutMenuBar property must contain a single AddMenu action that specifies the name of another macro that defines the menu itself.

Shortcut menus are not available to any object if the AllowShortcutMenus property is set to False.


HelpButton Property
WhatsThisButton Property

You can use the WhatsThisButton property to specify whether a Whats This button is added to a form's title bar.

Note   You can't display the Whats This button on the title bar of a form unless the MinMaxButtons property is set to None.

Setting

The WhatsThisButton property uses the following settings.

Setting	Description	Visual Basic
Yes	A Whats This help button appears on the title bar.	True (-1)
No	(Default) A Whats This help button doesn't appear on the title bar.	False (0)
You can set the WhatsThisButton property in the form's property sheet, a macro, or using Visual Basic.

This property can be set only in form Design view.

Remarks

Choosing the Whats This button from the title bar of a form causes the Help Select mouse pointer to appear. With the Help Select mouse pointer, you can click any control to access its custom Help topic specified by the control's HelpContextID property. If the control doesn't have a custom Help topic, the form's custom Help topic is displayed. If neither the form or the control has a custom Help topic, Microsoft Access Help is displayed.


ControlTipText Property

You can use the ControlTipText property to specify the text that appears in a screen tip when you hold the mouse pointer over a control.

Setting

You set the ControlTipText property using a string expression up to 255 characters long.

You can set the ControlTipText property in the control's property sheet, a macro, or using Visual Basic.

You can set the ControlTipText property in any view.

Remarks

The ControlTipText property provides an easy way to provide helpful information about controls on a form.

There are other ways to provide on-line assistance for a form or a control on a form. You can use the StatusBarText property to display information in the status bar about a control. To provide more extensive help for a form or control, use the HelpFile and HelpContextID properties.


Database Property
Database Properties

The Database properties allow you to provide additional information about your database. To view the Database properties click the Database Properties command on the File menu.

Setting

You can set these properties by entering information in the Summary or Custom tabs in the Database properties dialog box or using Visual Basic.

In Visual Basic, if a Database property has not already been set in the Database Properties dialog box, you must create the property using the CreateProperty method and append it to the Properties collection of a Document object. You set properties in the Summary tab using the SummaryInfo Document in the Documents collection. You set properties in the Custom tab using the UserDefined Document in the Documents collection. You must supply a name, datatype, and default value for a custom property before you can add it to your database. For more information, see the Specifics information in the Documents collection topic.

Note   You can only enter or edit the properties that appear under the Summary or Custom tabs. The other Database properties are read-only.

Remarks

The Database properties appear in the Database Properties dialog box under the following tabs:

General

This is the same information that is displayed when you right-click on a filename using the Windows Explorer and choose the Properties command. The only difference is that when viewed in Microsoft Access, the Attributes settings are read-only.

Summary

Choose the Summary tab to add summary information about your database. The information you enter is added to the SummaryInfo Document in the Documents collection. This information is similar to the summary information you can provide in other Microsoft Office applications. Summary information allows the user to better identify a database both from within Microsoft Access and to outside programs such as the Windows 95 FindFile program.

Statistics

Choose the Statistics tab to view information about your database. This information includes the date and time the active database was created, the last date and time it was modified, accessed, and printed.

Contents

Choose the Contents tab to see a list of the names of the objects contained in your database.

Custom

Choose the Custom tab to view, add, or modify custom database properties. The custom properties you enter become properties of the UserDefined Document in the Documents collection.


Database Properties Example

In the following example you can set or create a custom user-defined property that will appear on the Custom tab of the Database Properties dialog box. For example, you could call the SetCustomProperty function to add a new property called UserName to the UserDefined Document in the database. The arguments passed to the SetCustomProperty function are those required to execute the CreateProperty method.

Dim strName As String, strValue As String

' Set property name variable

strName = "LastUserName"

' Set property value variable

strValue = InputBox("Please enter your full name")

If SetCustomProperty(strName, dbText, strValue) = True Then

' Property was successfully set

Else

' Error occured trying to set property.

End If

Function SetCustomProperty(strPropName As String, intPropType _

As Integer, strPropValue As String) As Integer

Dim dbs As Database, cnt As Container

Dim doc As Document, prp As Property

Const conPropertyNotFound = 3270	' Property not found error

Set dbs = CurrentDb()	' Define Database object

Set cnt = dbs.Containers!Databases	' Define Container object

Set doc = cnt.Documents!UserDefined	' Define Document object

On Error GoTo SetCustom_Err

doc.Properties.Refresh

' Set custom property name. If an error occurs here it means the

' property does not exist and needs to be created and appended

' to the properties collection of the document object.

Set prp = doc.Properties(strPropName)

prp = strPropValue	' Set custom property value

SetCustomProperty = True

SetCustom_Bye:

Exit Function

SetCustom_Err:

If Err = conPropertyNotFound Then

Set prp = doc.CreateProperty(strPropName, _

intPropType, strPropValue)

doc.Properties.Append prp	' Append to collection

Resume Next

Else	' Unknown error

SetCustomProperty = False

Resume SetCustom_Bye

End If

End Function

The next example demonstrates how to display information from the Summary tab of the Database Properties dialog box. The application title, subject, and author are displayed in text box controls on a form. In this example, if the property has not already been set then "None" is returned from the procedure. If an unkown error occurs then a zero length string (" ") is returned.

Private Sub Form_Open(Cancel As Integer)

Dim strTitle As String, strSubject As String, strAuthor As String

strTitle = "Title"

strSubject = "Subject"

strAuthor = "Author"

Me!txtTitle = GetSummaryInfo(strTitle)

Me!txtSubject = GetSummaryInfo(strSubject)

Me!txtAuthor = GetSummaryInfo(strAuthor)

End Sub

Function GetSummaryInfo(strPropName As String) As String

Dim dbs As Database, cnt As Container

Dim doc As Document, prp As Property

Const conPropertyNotFound = 3270	' Property not found error

On Error GoTo GetSummary_Err

Set dbs = CurrentDb()	' Define Database object

Set cnt = dbs.Containers!Databases	' Define Container object

Set doc = cnt.Documents!SummaryInfo	' Define Document object

doc.Properties.Refresh

GetSummaryInfo = doc.Properties(strPropName)

GetSummary_Bye:

Exit Function

GetSummary_Err:

If Err = conPropertyNotFound Then

Set prp = doc.CreateProperty(strPropName, dbText, "None")

doc.Properties.Append prp	' Append to collection

Resume

Else	' Unknown error

GetSummaryInfo = ""

Resume GetSummary_Bye

End If

End Function


Object Properties

The Object properties provide general information about objects contained in the database window.

Setting

You can view the Object properties, and set the Description or Attributes properties, by clicking the Properties icon on the Database toolbar, clicking the Properties command on the View menu, or choosing the Properties command from the popup menu that appears when you right click on an object in the database window.

You can also specify or determine the Object properties using Visual Basic.

Note   You can only enter or edit the Description or Attributes properties. The other Object properties are set by Microsoft Access and are read-only.

Remarks

The objects in the database window are: Tables, Queries, Forms, Reports, Macros, and Modules. Each class of objects in the database is represented by a separate Document object within the Containers collection. For example, the Containers collection contains a Document object that represents all the forms in the database.

The Object properties available from the database window are:

Name

This is the name of the object and contains the setting from the objects Name property.

Type

This is the object type. Microsoft Access object types are: Form, Macro, Module, Query, Report, and Table.

Description

This is the object's description and is the same as the Description property. For tables or queries, you can also set the object's Description property in the object's property sheet. An object's description also appears next to the object's name in the database window if the Details command is selected from the View menu.

Created

This is the date that the object was created. For tables or queries, this property is the same as the DateCreated property.

Modified

This is the date that the object was last modified. For tables or queries this property is the same as the LastUpdated property.

Owner

This is the owner of the object. For more information, see the Owner property

Attributes

This property specifies whether the object is hidden or visible and whether the object is replicable in a database replica.

If you set the hidden attribute to True, the object will not appear in the database window. To display hidden objects in the database window choose the Options command on the Tools menu, click the View tab, and then select the Hidden objects check box. The icons for hidden objects will be displayed with a dimmed outline in the database window. You can then turn the hidden attribute off, making the object visible in the database window.


Object Properties Example

The following example uses the PrintObjectProperties subroutine to print the values of an object's Object properties to the Debug Window. The subroutine requires the object type and object name as arguments.

Dim strObjectType As String

Dim strObjectName As String

Dim strMsg As String

strMsg = "Enter object type (e.g., Forms, Macros, " _

& "Modules, Queries, Reports, Tables)"

' Get object type

strObjectType = InputBox(strMsg)

strMsg = "Enter the name of a Form, Macro, Module, " _

& "Query, Report, or Table"

' Get object name from user

strObjectName = InputBox(strMsg)

' Pass object type and object name to the PrintObjectProperties

' subroutine

PrintObjectProperties strObjectType, strObjectName

Sub PrintObjectProperties(strObjectType As String, strObjectName _

As String)

Dim dbs As Database, cnt As Container, doc As Document

Dim intI As Integer

Dim strTabChar As String

Set dbs = CurrentDb

strTabChar = Chr$(9)

' Set container object variable

Set cnt = dbs.Containers(strObjectType)

' Set document object variable

Set doc = cnt.Documents(strObjectName)

doc.Properties.Refresh

' Print the object name to the Debug window

Debug.Print doc.Name

' Print each object property to Debug window

For intI = 0 to doc.Properties.Count - 1

Debug.Print strTabChar & doc.Properties(intI).Name & " = " _

& doc.Properties(intI).Value

Next intI

End Sub


Application Property

You can use the Application property in Visual Basic to access the active Microsoft Access Application object and its related properties.

Setting

The Application property is set by Microsoft Access and is read-only.

Remarks

Each Microsoft Access object has an Application property that returns the current Application object. You can use this property to access any of the Application object properties. For example, you could refer to the menu bar for the Application object from the current form using the following syntax:

Me.Application.MenuBar


Application and DBEngine Properties Example

This example demonstrates the use of the Application and DBEngine properties to display the DBEngine properties in a message box.

Private Sub Command1_Click()

Dim x As Integer

x = DisplayApplicationInfo(Me)

End Sub

Function DisplayApplicationInfo(obj As Object) As Integer

Dim apl As Object, intI As Integer, strProps As String

On Error Resume Next

' Form application property

Set apl = obj.Application

MsgBox "Application visible Property = " & apl.Visible

If apl.UserControl = True Then

For intI = 0 To apl.DBEngine.Properties.Count - 1

strProps = strProps & apl.DBEngine.Properties(intI).Name & ", "

Next intI

End If

MsgBox Left(strProps, Len(strProps) - 2) & ".", vbOK, "DBEngine Properties"

End Function


DBEngine Property

You can use the DBEngine property in Visual Basic to access the current DBEngine object and its related properties.

Setting

The DBEngine property is set by Microsoft Access and is read-only.

Remarks

The DBEngine property of the Application object represents the Microsoft Jet database engine. The DBEngine object is the top-level object in the Data Access Object (DAO) model and it contains and controls all other objects in the hierarchy of data access objects.


UserControl Property

You can use the UserControl property in Visual Basic to determine whether the current Microsoft Access application was started by the user or by another application using OLE Automation.

Setting

The UserControl property uses the following settings.

Setting 	Description

True (-1)	The current application was started by the user.

False (0)	The current application was started by another
application using OLE Automation.

You can determine the UserControl property setting only using Visual Basic.

This property is read-only in all views.

Remarks

When an application is launched by the user, the Visible and UserControl properties of the Application object are both set to True. When the UserControl property is set to True, it is not possible to set the Visible property of the Application object to False.

When an Application object is created using OLE Automation, the Visible and UserControl properties of the Application object are both set to False.


Visible Property (Application Object)

You can use the Visible property of the Application object to specify or determine whether a Microsoft Access application is visible.

Setting

The Visible property uses the following settings.

Setting 	Description

True (-1)	The application is visible.

False (0)	The application isn't visible.

You can set the Visible property of the Application object only using Visual Basic.

Remarks

When an application is launched by the user, the Visible and UserControl properties of the Application object are both set to True. When the UserControl property is set to True, it is not possible to set the Visible property of the Application object to False.

When an Application object is created using OLE Automation, the Visible and UserControl properties of the Application object are both set to False.

Note   When the Visible property of the Application object is set to False, the application is minimized but is not hidden from the user.


CodeContextObject Property

You can use the CodeContextObject property to determine the object in which a macro or Visual Basic code is executing.

Setting

The CodeContextObject property is set by Microsoft Access and is read only.

Remarks

The ActiveForm and ActiveReport properties of the Screen object object always return the object that currently has the focus. The object with the focus may or may not be the object where a macro or Visual Basic code is currently running, for example, when Visual Basic code runs in the Timer event on a hidden form.


CodeContextObject Property Example

In this example the CodeContextObject property is used in a function to identify the name of the object in which an error occured. The object name is then used in the message box title as well as in the body of the error message. The Error statement is used in the Command1_Click() event to generate the error for this example.

Private Sub Command1_Click()

On Error goto Command1_Err

Error 11	' Generate divide by zero error

Exit Sub

Command1_Err:

If ErrorMessage("Command1_Click() Event", vbYesNo + _

vbInformation, Err) = vbYes then

Exit Sub

Else

Resume

End If

End Sub

Function ErrorMessage(strText As String, intType As Integer, _

intErrVal As Integer) As Integer

Dim objCurrent As Object

Dim strMsgboxTitle As String

Set objCurrent = CodeContextObject

strMsgboxTitle = "Error in " & objCurrent.Name

strText = strText & "Error #" & intErrVal & _

" occured in " & 	objCurrent.Name

ErrorMessage = MsgBox(strText, intType, strMsgboxTitle)

Err = 0

End Function


Action Property

You can use the Action property in Visual Basic to specify the operation to perform on an OLE object.

Setting

The Action property uses the following settings.

Constant	Value	Description
acOLECreateEmbed	0	Creates an embedded object. To use this setting, you must first set the control's OLETypeAllowed property to acOLEEmbedded or acOLEEither. Set the Class property to the type of OLE object you want to create. You can use the SourceDoc property to use an existing file as a template.
acOLECreateLink	1	Creates a linked OLE object from the contents of a file. To use this setting, you must first set the control's OLETypeAllowed and SourceDoc properties. Set the OLETypeAllowed property to acOLELinked or acOLEEither. The SourceDoc property specifies the file used to create the OLE object. You can also set the control's SourceItem property (for example, to specify a row-and-column range if the object you're creating is a Microsoft Excel worksheet). When you create an OLE object using this setting, the control displays a metafile graphic image of the file specified by the control's SourceDoc property. If you save the OLE object, only the link information, such as the name of the application that supplied the object and the name of the linked file, is saved because the control contains an image of the data but no source data.
acOLECopy	4	Copies the object to the Clipboard. When you copy an OLE object to the Clipboard, all the data and link information associated with the object is placed on the Clipboard as well. You can copy both linked and embedded objects onto the Clipboard. Using this setting is equivalent to clicking Copy on the Edit menu.
acOLEPaste	5	Pastes data from the Clipboard to the control. If the paste operation is successful, the control's OLEType property is set to acOLELinked or acOLEEmbedded. If the paste operation isn't successful, the OLEType property is set to acOLENone. Using this setting is equivalent to clicking Paste on the Edit menu.
acOLEUpdate	6	Retrieves the current data from the application that supplied the object and displays that data as a metafile graphic in the control.
acOLEActivate	7	Opens an OLE object for an operation, such as editing. To use this setting, you must first set the control's Verb property. The Verb property specifies the operation to perform when the OLE object is activated.
acOLEClose	9	Closes an OLE object and ends the connection with the application that supplied the object. This setting applies to embedded objects only. Using this setting is equivalent to clicking Close on the object's Control menu.
acOLEDelete	10	Deletes the specified OLE object and frees the associated memory. This setting enables you to explicitly delete an OLE object. Objects are automatically deleted when a form is closed or when the object is updated to a new object. You can't use the Action property to delete a bound OLE object from its underlying table or query.
acOLEInsertObjDlg	14	Displays the Insert Object dialog box. In Form view or Datasheet view, you display this dialog box to enable the user to create a new object or to link or embed an existing object. You can use the control's OLETypeAllowed property to determine the type of object the user can create (with the constant acOLELinked, acOLEEmbedded, or acOLEEither) using this dialog box.
acOLEPasteSpecialDlg	15	Displays the Paste Special dialog box. In Form View or Datasheet view, you display this dialog box to enable the user to paste an object from the Clipboard. The dialog box provides several options, including pasting either a linked or embedded object. You can use the control's OLETypeAllowed property to determine the type of object that can be pasted (with the constant acOLELinked, acOLEEmbedded, or acOLEEither) using this dialog box.
acOLEFetchVerbs	17	Updates the list of verbs an OLE object supports. To display the list of verbs, use the ObjectVerbs and ObjectVerbsCount properties.
You can set the Action property only using Visual Basic. The Action property setting has an Integer data type value.

The Action property isn't available in Design view but can be read or set in other views.

Remarks

When a control is disabled or locked, you can't use some Action property settings. The following table indicates which settings are allowed or not allowed under these conditions.

Setting	Disabled	Locked
acOLECreateEmbed	Not allowed	Not allowed
acOLECreateLink	Not allowed	Not allowed
acOLECopy	Allowed	Allowed
acOLEPaste	Not allowed	Not allowed
acOLEUpdate	Not allowed	Not allowed
acOLEActivate	Allowed	Allowed
acOLEClose	Not allowed	Allowed
acOLEDelete	Not allowed	Not allowed
acOLEInsertObjDlg	Not allowed	Not allowed
acOLEPasteSpecialDlg	Not allowed	Not allowed
acOLEFetchVerbs	Not allowed	Allowed


AutoActivate Property

You can use the AutoActivate property to specify how the user can activate an OLE object.

Setting

The AutoActivate property uses the following settings.

Setting	Description	Visual Basic
Manual	The OLE object isn't activated when it receives the focus or when the user double-clicks the control. You can activate an OLE object only using Visual Basic by setting the control's Action property to acOLEActivate.	0
GetFocus	(For unbound object frame and chart controls only) If the control contains an OLE object, the application that supplied the object is activated when the control receives the focus.	1
Double-Click	(Default) If the control contains an OLE object, the application that supplied the object is activated when the user double-clicks the control or presses CTRL+ENTER when the control has the focus.	2
You can set this property using the property sheet, a macro, or Visual Basic. You can also set this property in a control's default control style.

The AutoActivate property can be set only in Design view.

Remarks

Some OLE objects can be activated from within the control. When such an object is activated, the object can be edited (or some other operation can be performed) from inside the boundaries of the control. This feature is called in-place activation. If an object supports in-place activation, see the documentation for the application that created the object for information about using this feature.

Using Visual Basic, you can determine if a control contains an object by checking the setting of its OLEType property.

Note   If you set a control's AutoActivate property to Double-Click and specify a DblClick event for the control, the DblClick event occurs before the object is activated.


Class Property

You can use the Class property to specify or determine the class name of an embedded OLE object.

Setting

The Class property setting is a string expression that you or Microsoft Access supplies when you create or paste an OLE object.

You can set the Class property using the property sheet, a macro, or Visual Basic.

Remarks

A class name defines the type of OLE object. For example, Microsoft Excel version 5.0 supports several types of OLE objects, including worksheets and charts. Their class names are "Excel.Sheet" and "Excel.Chart" respectively. When you create an OLE object in Design view using the Paste Special command on the Edit menu or the Object command on the Insert menu, Microsoft Access enters the class name of the new object in the property sheet.

Note   To determine the class name of an OLE object, see the documentation for the application supplying the object.

The Class property setting is updated when you copy an object from the Clipboard. For example, if you paste a Microsoft Excel chart from the Clipboard into an OLE object that previously contained a Microsoft Excel worksheet, the Class property setting changes from "Excel.Sheet" to "Excel.Chart". You can paste an object from the Clipboard using Visual Basic by setting the control's Action property to acOLEPaste or acOLEPasteSpecialDlg.


Item Property

You can use the Item property to get a description of the linked data displayed in a unbound object frame.

Setting

The Item property setting is a string expression and is read-only in all views.

Remarks

The description of a linked object frame depends on the kind of OLE object it is linked to. For example, if you link it to cells in a Microsoft Excel worksheet, Microsoft Access displays the cell data in the object frame, and the Item property identifies the linked cells using the row-and-column format. For a chart, the Item property setting is the word "Chart". For a graphic, the setting is the coordinates of the linked graphic area.

Note   The data for a linked OLE object is displayed in the frame but is stored by the application that created the data. To change the data, you must use that application.

When you link an OLE object to an object frame using the Paste Special command on the Edit menu, Microsoft Access sets the SourceObject, OLEClass, and Item properties. The following table shows typical property settings for various OLE objects.

Object	SourceObject property	OLEClass property	Item property
Worksheet	C:\Excel\Xls\Mywrksht.xls	Microsoft Excel Worksheet	R1C1:R7C4
Chart	C:\Excel\Xls\Mychart.xlc	Microsoft Excel Chart	Chart
Graphic	C:\Windows\Mybitmap.bmp	Paintbrush Picture	0 0 72 71


lpOLEObject Property

You can use the lpOLEObject property in Visual Basic to determine the memory address of an OLE object. The lpOLEObject property returns a pointer to IOLEObject.

Setting

You can use the lpOLEObject property to refer to the address of the active OLE object. If no object is displayed, the setting is 0. The lpOLEObject property setting is a Long data type value specified by Microsoft Access.

This property setting isn't available in Design view and is read-only in other views.

Remarks

In the OLE dynamic link libraries (DLLs), many function calls require the address of the OLE object as an argument. You can pass the value specified by the lpOLEObject property when making application programming interface (API) calls to the OLE DLLs.

Note   If an API call is made to a function that makes a callback to the control, the results will be unpredictable.


Object Property

You can use the Object property in Visual Basic to specify a linked or embedded OLE Automation object in a control.

Setting

The Object property setting is a Object data type value that specifies an OLE Automation object used in OLE Automation tasks.

The Object property setting is read-only in all views.

Remarks

You perform OLE Automation tasks on an OLE Automation object using properties and methods the object supports. For information on which properties and methods an OLE Automation object supports, see the documentation for the application that created the object.


Object Property Example

The following example uses the Object property of an unbound object frame named OLE1. Customer name and address information is inserted into an embedded word document formatted as a form letter with placeholders for the name and address information and boilerplate text in the body of the letter. The procedure replaces the address information for each record and prints the form letter. It doesn't save copies of the printed form letter.

Sub PrintFormLetter_Click()

Dim objWord As Object

Dim strCustomer As String, strAddress As String

Dim strCity As String, strRegion As String

' Assign the object property of control to variable.

Set objWord = Me!OLE1.Object.Application.Wordbasic

' Assign customer address information to variables.

Me!CompanyName.SetFocus

strCustomer = Me!CompanyName.Text

Me!Address.SetFocus

strAddress = Me!Address.Text

Me!City.SetFocus

strCity = Me!City.Text & ", "

Me!Region.SetFocus

If Not IsNull(Me!Region.Text) Then

strRegion = Me!Region.Text

Else

Me!Country.Setfocus

strRegion = Me!Country.Text

End If

Me!OLE1.Action = acOLEActivate	' Activate OLE control.

objWord.StartOfDocument

objWord.LineDown 2

objWord.EndOfLine 1

objWord.Insert strCustomer	' Insert customer name.

objWord.LineDown

objWord.StartOfLine

objWord.EndOfLine 1

objWord.Insert strAddress	' Insert address.

objWord.LineDown

objWord.StartOfLine

objWord.EndOfLine 1

objWord.Insert strCity & strRegion	' Insert City and Region.

objWord.FilePrint	' Print Word document.

objWord.FileClose

Set objWord = Nothing

End Sub


ObjectVerbs Property

You can use the ObjectVerbs property in Visual Basic to determine the list of verbs an OLE object supports. A verb, such as edit or play, specifies an operation a user can perform on an OLE object.

Setting

The ObjectVerbs property setting is a zero-based string array.

This property setting isn't available in Design view and is read-only in other views.

Remarks

You can use the ObjectVerbs property with the ObjectVerbsCount property to display a list of the verbs supported by an OLE object. The Verb property uses this list of verbs to determine which operation to perform when an OLE object is activated (when the Action property is set to acOLEActivate).

The Verb property setting is the position of a particular verb in the list of verbs returned by the ObjectVerbs property. For example, 1 specifies the first verb in the list (the Visual Basic command ObjectVerbs(0), or the first verb in the ObjectVerbs property array), 2 specifies the second verb in the list (the Visual Basic command ObjectVerbs(1), or the second verb in the ObjectVerbs property array), and so on.

The first verb in the ObjectVerbs property array, called by the Visual Basic command ObjectVerbs(0), is the default verb. If the Verb property hasn't been set, this verb specifies the operation performed when the OLE object is activated.

Applications that expose OLE objects typically include the Object command on the Edit menu. When the user clicks this command, a submenu displays the object's verbs. You can use the ObjectVerbs and ObjectVerbsCount properties to display a list of verbs in a form or report instead of on a menu.

The list of verbs an object supports varies, depending on the state of the object. To update the list of verbs an object supports, set the control's Action property to acOLEFetchVerbs. Be sure to update the list of verbs before presenting it to the user.


ObjectVerbs, ObjectVerbsCount Properties Example

The following example returns the verbs supported by the OLE object in the OLE1 control and displays each verb in a message box.

Function GetVerbList(frm As Form) As Integer

Dim intX As Integer, intNumVerbs As Integer

Dim strVerbListArray() As String

frm!OLE1.Action = acOLEFetchVerbs   ' Update verb list.

intNumVerbs = frm!OLE1.ObjectVerbsCount

ReDim strVerbListArray(intNumVerbs)

For intX = 0 To intNumVerbs - 1 ' For each verb.

strVerbListArray(intX) = frm!OLE1.ObjectVerbs(intX)  ' Return verb.

MsgBox strVerbListArray(intX)  ' Display verb in message box.

Next intX

End Function


ObjectVerbsCount Property

You can use the ObjectVerbsCount property in Visual Basic to determine the number of verbs supported by an OLE object. A verb, such as edit or play, specifies an operation a user can perform on an OLE object.

Setting

The ObjectVerbsCount property setting is an Integer data type value that specifies the number of elements in the ObjectVerbs property array.

This property setting isn't available in Design view and is read-only in other views.

Remarks

The list of verbs an OLE object supports may vary, depending on the state of the object. To update the list of supported verbs, set the control's Action property to acOLEFetchVerbs.


OLEClass Property

You can use the OLEClass property to obtain a description of the kind of OLE object contained in a chart or an unbound object frame.

Setting

This property is set automatically in the property sheet to a string expression when you click Object on the Insert menu to add an OLE object to a form. The OLEClass property setting is read-only in all views.

Remarks

The OLEClass property and the Class property are similar but not identical. The OLEClass property setting is a general description of the OLE object while the Class property setting is the name used to refer to the OLE object in Visual Basic. Examples of OLEClass property settings are Microsoft Excel Chart, Microsoft Word Document, and Paintbrush Picture.


OLEType Property

You can use the OLEType property to determine if a control contains an OLE object, and, if so, whether the object is linked or embedded.

Setting

The OLEType property uses the following settings.

Setting	Description	Visual Basic
Linked	The control contains a linked object. All the object's data is managed by the application that created it.	0
Embedded	The control contains an embedded object. All the object's data is managed by Microsoft Access.	1
None	The control doesn't contain an OLE object.	3
The OLEType property is read-only in all views.

Remarks

When creating an OLE object, use the OLETypeAllowed property to determine what type of object a control can contain.


OLEType Property Example

The following example illustrates how to display the Insert Object dialog box and how to display an error message if the Cancel button in the Insert Object dialog box is clicked, so no object will be created.

Sub InsertObject_Click()

Dim conUserCancelled As Integer

conUserCancelled = 2001	' Error message returned when user cancels.

On Error GoTo ButtonErr	' Set up error handler.

If OLE1.OLEType = 3 Then	' No OLE Object created.

OLE1.Action = acOLEInsertObjDlg	' Display Insert Object dialog box.

End If

Exit Sub

ButtonErr:

If Err = conUserCancelled Then	' Display message.

MsgBox "You pressed the Cancel button, no object was created."

End If

Resume Next

End Sub


OLETypeAllowed Property

You can use the OLETypeAllowed property to specify the type of OLE object a control can contain.

Setting

The OLETypeAllowed property uses the following settings.

Setting	Description	Visual Basic
Linked	The control can contain only a linked object.	0
Embedded	The control can contain only an embedded object.	1
Either	(Default) The control can contain either a linked or an embedded object.	2
You can set the OLETypeAllowed property using the property sheet, a macro, or Visual Basic. You can also set this property in a control's default control style.

Note   For unbound object frames, you can't change the OLETypeAllowed setting after an object is created. For bound object frames, you can change the setting after the object is created. Changing the OLETypeAllowed property setting only affects new objects that you add to the control.

Remarks

To determine the type of OLE object a control already contains, you can use the OLEType property.


SourceItem Property

You can use the SourceItem property to specify the data within a file to be linked when you create a linked OLE object.

Setting

You can set the SourceItem property by specifying data in units recognized by the application supplying the object. For example, when you link to Microsoft Excel, you specify the SourceItem property setting using a cell or cell-range reference such as R1C1 or R3C4:R9C22 or a named range such as Revenues.

Note   To determine the syntax to describe a unit of data for a particular object, see the documentation for the application that created the object.

You can set this property using the property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property using a string expression.

Remarks

The control's OLETypeAllowed property must be set to Linked or Either when you use this property. Use the control's SourceDoc property to specify the file to link.


Verb Property

You can use the Verb property to specify the operation to perform when an OLE object is activated, which is permitted when the control's Action property is set to acOLEActivate.

Setting

You can set the Verb property by specifying an Integer data type value indicating the position of a verb in the list of verbs returned by the ObjectVerbs property. A verb, such as edit or play, specifies an operation a user can perform on an OLE object. you can set the Verb property to 1 to specify the first verb in the list, you can set it to 2 to specify the second verb in the list, and so on.

You can set the Verb property using the property sheet, a macro, or Visual Basic. You can also set this property using the default control style.

If you don't set the ObjectVerbs property, you can set the Verb property to one of the following values to indicate the operation to perform. These values specify the standard verbs supported by all objects.

Constant	Value	Description
acOLEVerbPrimary	0	Performs the default operation for the object.
acOLEVerbShow	-1	Activates the object for editing.
acOLEVerbOpen	-2	Opens the object in a separate application window.
acOLEVerbHide	-3	For embedded objects, hides the application that created the object.
With some application's objects, you can use these additional values.

Constant	Value	Description
acOLEVerbInPlaceUIActivate	-4	Activates the object for editing within the control. The menus and toolbars of the object application become available in the container application.
acOLEVerbInPlaceActivate	-5	Activates the object within the control. The menus and toolbars of the object application aren't available in the container application.
Remarks

Each object supports its own set of verbs. For example, many objects support the verbs edit and play. You can use the ObjectVerbs and ObjectVerbsCount properties to find out which verbs are supported by an object.

Microsoft Access automatically uses an object's default verb if the user double-clicks an object for which the AutoActivate property is set to Double-Click.


FastLaserPrinting Property

You can use the FastLaserPrinting property to specify whether lines and rectangles are replaced by text character lines [image] similar to underscore (_) and vertical bar (|) characters [image] when you print a form or report using most laser printers.

Setting

The FastLaserPrinting property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) Lines and rectangles are replaced by text character lines.	True (-1)
No	Lines and rectangles aren't replaced by text character lines.	False (0)
You can set this property only in Design view using the property sheet, a macro, or Visual Basic.

Remarks

The FastLaserPrinting property affects any line or rectangle on a form or report, including controls that include these shapes (for example, a border around a text box).

You use this property to speed printing; replacing lines and rectangles with text character lines can make printing much faster. When the FastLaserPrinting property is set to No, Microsoft Access prints lines and rectangles as graphics. When the this property is set to Yes, lines and rectangles are printed as text character lines, resulting in faster printing.

Note   This property has no effect on PostScript printers, dot-matrix printers, or earlier versions of laser printers that don't support text character lines.

When this property is set to Yes and the form or report being printed has overlapping rectangles or lines, the rectangles or lines on top don't erase the rectangles or lines they overlap. If you require overlapping graphics on your report, set the FastLaserPrinting property to No.


FastLaserPrinting Property Example

The following example demonstrates setting the FastLaserPrinting property for the Invoice report while in report Design view.

DoCmd.OpenReport "Invoice", acDesign

Reports!Invoice.FastLaserPrinting = True

DoCmd.Close acReport, "Invoice", acSaveYes


FormatCount Property

You can use the FormatCount property to determine the number of times the OnFormat property has been evaluated for the current section on a report.

Setting

You can use this property only in a macro or an event procedure specified by a section's OnFormat property setting.

The FormatCount property setting has a Long data type value.

This property isn't available in Design view and is read-only in other views.

Remarks

Microsoft Access increments the FormatCount property each time the OnFormat property setting is evaluated for the current section. As the next section is formatted, Microsoft Access resets the FormatCount property to 1.

Under some circumstances, Microsoft Access formats a section more than once. For example, you might design a report in which the KeepTogether property for the detail section is set to Yes. When Microsoft Access reaches the bottom of a page, it formats the current detail section once to see if it will fit. If it doesn't fit, Microsoft Access moves to the next page and formats the detail section again. In this case, the setting for the FormatCount property for the detail section is 2 because it was formatted twice before it was printed.

Use the FormatCount property to ensure that a time-consuming operation that affects formatting gets executed only once for a section. In the following example, the DLookup function is evaluated only when the FormatCount property is set to 1.

If FormatCount = 1 Then

If DLookup("[CustomerName]","[Customers]", "[CustomerID] = Reports![Customers]![CustomerID]") = 7 Then

[CustomerName].FontWeight = Bold

Else

[CustomerName].FontWeight = Normal

End If
End If

If you include the Else block in this procedure, you don't need to create an OnRetreat event procedure for the section.

Tip   To calculate totals, use the PrintCount property.


MoveLayout, NextRecord, PrintSection Properties

You can use combinations of these property settings in Visual Basic to specify or change a report's layout when the report is previewed, printed, or saved to a file:

MoveLayout [image] This property specifies whether Microsoft Access should move to the next printing location on the page.

NextRecord [image] This property specifies whether a section should advance to the next record.

PrintSection [image] This property specifies whether a section should be printed on the page.

Setting

The MoveLayout property uses the following settings.

Setting	Description

True (-1)	(Default) The section's Left and Top properties are advanced to the next print location.

False (0)	The section's Left and Top properties are unchanged.

The NextRecord property uses the following settings.

Setting	Description

True	(Default) The section advances to the next record.

False	The section doesn't advance to the next record.

The PrintSection property uses the following settings.

Setting	Description

True	(Default) The section is printed on the page.

False	The section isn't printed.

To set these properties, specify a macro or event procedure for a section's OnFormat property.

Microsoft Access sets these properties to True before each section's Format event.

Remarks

These properties are useful when you want to use a report as a template into which you write data from a macro or Visual Basic as you print.

The following table shows the result of different setting combinations for these properties.

MoveLayout	NextRecord	PrintSection	Description
True	True	True	(Default) Move to the next print location, get the next record, and print the data.
True	False	True	Move to the next print location, don't advance to the next record, but print the data. This combination is typically used when the data in a section requires more space than the layout allows and you want to print the remaining data in the space that would otherwise be occupied by the next section.
False	True	False	Skip a record without leaving a blank space on the page.
True	True	False	Skip a record and leave a blank space on the page.
True	False	False	Leave a blank space without skipping a record, as in a sparse matrix.
False	True	True	Print the current record on top of the last record as an overlay.
False	False	True	Not allowed.
False	False	False	Not allowed.


PrintCount Property

You can use the PrintCount property to identify the number of times the OnPrint property has been evaluated for the current section of a report.

Setting

You can use this property only in a macro or an event procedure specified by a section's OnPrint property setting.

The PrintCount property setting has a Long data type value.

This property isn't available in Design view and is read-only in all other views.

Remarks

Microsoft Access increments the PrintCount property each time the OnPrint property setting is evaluated for the current section. As the next section is printed, Microsoft Access resets PrintCount property to 0.

The PrintCount property is incremented, for example, when the KeepTogether property is set to No for the current section and the section is printed on more than one page. If you print a report containing order information, you might keep a running total of the order amounts. The following example shows how you can use the PrintCount property to make sure the value of each order is added only once.

If Reports![MyReport].PrintCount = 1 Then
RunningTotal = RunningTotal + OrderAmount
End If


PrtDevMode Property

You can use the PrtDevMode property to set or return printing device mode information specified for a form, report, or module in the Print Setup dialog box.

Note   It is strongly recommended that you consult the Win32 Software Development Kit for complete documentation on the PrtDevMode, PrtDevNames, and PrtMip properties.

The PrtDevMode property applies only to tables and queries in Datasheet view and reports and forms.

Setting

The PrtDevMode property setting is a 94-byte structure that mirrors the DEVMODE structure defined in the Win32 Software Development Kit. For complete information on the PrtDevMode property members, consult the Win32 Software Development Kit.

The PrtDevMode property uses the following members.

Member	Description

DeviceName	A 32-character string that specifies the name of the device the driver supports [image] for example, "HP LaserJet IIISi" if the Hewlett-Packard LaserJet IIISi is the specified printer. Each printer driver has a unique string.

SpecVersion	An Integer that specifies the version number of the DEVMODE structure in the Win32 Software Development Kit.

DriverVersion	An Integer that specifies the printer driver version number assigned by the printer driver developer.

Size	An Integer that specifies the size, in bytes, of the DEVMODE structure. (This value doesn't include the optional dmDriverData member for device-specific data, which can follow this structure.) If an application manipulates only the driver-independent portion of the data, you can use this member to find out the length of this structure without having to account for different versions.

DriverExtra	An Integer that specifies the size, in bytes, of the optional dmDriverData member for device-specific data, which can follow this structure. If an application doesn't use device-specific information, you set this member to 0.

Fields	A Long value that specifies which of the remaining members in the DEVMODE structure have been initialized. It can be any combination of specific constants or none of them. For available constants, see the Fields member constants.

Orientation	An Integer that specifies the orientation of the paper. It can be either 1 (portrait) or 2 (landscape).

PaperSize	An Integer that specifies the size of the paper to print on. You can set this member to 0 if the length and width of the paper are specified by the PaperLength and PaperWidth members, respectively. Otherwise, you can set the PaperSize member to a predefined value. For available values, see the PaperSize member values.

PaperLength	An Integer that specifies the paper length in units of 1/10 of a millimeter. This member overrides the paper length specified by the PaperSize member for custom paper sizes or for devices such as dot-matrix printers that can print on a variety of paper sizes.

PaperWidth	An Integer that specifies the paper width in units of 1/10 of a millimeter. This member overrides the paper width specified by the PaperSize member.

Scale	An Integer that specifies the factor by which the printed output will be scaled. The apparent page size is scaled from the physical page size by a factor of Scale/100. For example, a piece of paper measuring 8.5 by 11 inches (letter-size) with a Scale value of 50 would contain as much data as a page measuring 17 by 22 inches because the output text and graphics would be half their original height and width.

Copies	An Integer that specifies the number of copies printed if the printing device supports multiple-page copies.

DefaultSource	An Integer that specifies the default bin from which the paper is fed. For available values, see the DefaultSource member values.

PrintQuality	An Integer that specifies the printer resolution. See the PrintQuality member values of appropriate device-independent values.

Color	An Integer. For a color printer, specifies whether the output is printed in color. For available values, see the Color member values.

Duplex	An Integer. For a printer capable of duplex printing, specifies whether the output is printed on both sides of the paper. For available values, see the Duplex member values.

YResolution	An Integer that specifies the y-resolution of the printer in dots per inch (dpi). If the printer initializes this member, the PrintQuality member specifies the x-resolution of the printer in dpi.

TTOption	An Integer that specifies how TrueType fonts will be printed. For available values, see the TTOption member values.

Collate	An Integer that specifies whether collation should be used when printing multiple copies. Using uncollated copies provides faster, more efficient output, since the data is sent to the printer just once.

FormName	A 16-character string that specifies the name of the form to use; for example, "Letter" or "Legal".

Pad	A Long Integer value.

Bits	A Long value that specifies in bits per pixel the color resolution of the display device.

PW	A Long value that specifies the width, in pixels, of the visible device surface.

PH	A Long value that specifies the height, in pixels, of the visible device surface.

DFI	A Long value that specifies the device's display mode.

DFR	A Long value that specifies the frequency, in hertz (cycles per second), of the display device in a particular mode.

You can set the PrtDevMode property using a macro or an event procedure.

This property setting is read/write in Design view and read-only in other views.

Caution   Printer drivers can add device-specific data immediately following the DEVMODE structure. It is important that information that may be contained after the first 94 bytes not be overwritten.

Remarks

Only printer drivers that export the ExtDeviceMode function use the DEVMODE structure.

An application can retrieve the paper sizes and names supported by a printer by calling the DeviceCapabilities function with the DC_PAPERS, DC_PAPERSIZE, and DC_PAPERNAMES values.

Before setting the value of the dmTTOption member, applications should find out how a printer driver can use TrueType fonts by calling the DeviceCapabilities function using the DC_TRUETYPE value.


Constants for the Fields Member

A printer driver supports only those members that are appropriate for the printer technology.

Constant	Value

DM_ORIENTATION	&H0000001

DM_PAPERSIZE	&H0000002

DM_PAPERLENGTH	&H0000004

DM_PAPERWIDTH	&H0000008

DM_SCALE	&H0000010

DM_COPIES	&H0000100

DM_DEFAULTSOURCE	&H0000200

DM_PRINTQUALITY	&H0000400

DM_COLOR	&H0000800

DM_DUPLEX	&H0001000

DM_YRESOLUTION	&H0002000

DM_TTOPTION	&H0004000

DM_COLLATE	&H0008000

DM_FORMNAME	&H0010000


Values for the PaperSize Member

Value	Paper size

1	Letter (8.5 x 11 in.)

2	Letter Small (8.5 x 11 in.)

3	Tabloid (11 x 17 in.)

4	Ledger (17 x 11 in.)

5	Legal (8.5 x 14 in.)

6	Statement (5.5 x 8.5 in.)

7	Executive (7.25 x 10.5 in.)

8	A3 (297 x 420 mm)

9	A4 (210 x 297 mm)

10	A4 Small (210 x 297 mm)

11	A5 (148 x 210 mm)

12	B4 (250 x 354)

13	B5 (182 x 257 mm)

14	Folio (8.5 x 13 in.)

15	Quarto (215 x 275 mm)

16	11 x 17 in.

18	Note (8.5 x 11 in.)

19	Envelope #9 (3.875 x 8.875 in.)

20	Envelope #10 (4.125 x 9.5 in.)

21	Envelope #11 (4.5 x 10.375 in.)

22	Envelope #12 (4.25 x 11 in.)

23	Envelope #14 (5 x 11.5 in.)

24	C size sheet

25	D size sheet

26	E size sheet

27	Envelope DL (110 x 220 mm)

28	Envelope C5 (162 x 229 mm)

29	Envelope C3 (324 x 458 mm)

30	Envelope C4 (229 x 324 mm)

31	Envelope C6 (114 x 162 mm)

32	Envelope C65 (114 x 229 mm)

33	Envelope B4 (250 x 353 mm)

34	Envelope B5 (176 x 250 mm

35	Envelope B6 (176 x 125 mm)

36	Envelope (110 x 230 mm)

37	Envelope Monarch (3.875 x 7.5 in.)

38	6-3/4 Envelope (3.625 x 6.5 in.)

39	US Std Fanfold (14.875 x 11 in.)

40	German Std Fanfold (8.5 x 12 in.)

41	German Legal Fanfold (8.5 x 13 in.)

256	User-defined


Values for the DefaultSource Member

Value	Meaning

1	Upper or only one bin

2	Lower bin

3	Middle bin

4	Manual bin

5	Envelope bin

6	Envelope manual bin

7	Automatic bin

8	Tractor bin

9	Small-format bin

10	Large-format bin

11	Large-capacity bin

14	Cassette bin

256	Device-specific bins start here


Values for the PrintQuality Member

Value	Resolution

-4	High

-3	Medium

-2	Low

-1	Draft


Values for the Color Member

Value	Meaning

1	Color

2	Monochrome


Values for the Duplex Member

Value	Meaning

1	Simplex

2	Horizontal

3	Vertical


Values for the TTOption Member

Value	Meaning

1	Print TrueType fonts as graphics. This is the default for dot-matrix printers.

2	Download TrueType fonts as soft fonts. This is the default for Hewlett-Packard printers that use Printer Control Language (PCL).

3	Substitute device fonts for TrueType fonts. This is the default for PostScript printers.


PrtDevMode Property Example

The following example uses the PrtDevMode property to check the user-defined page size for a report.

Type str_DEVMODE
RGB As String * 94
End Type

Type type_DEVMODE
dmDeviceName As String * 16
dmSpecVersion As Integer
dmDriverVersion As Integer
dmSize As Integer
dmDriverExtra As Integer
dmFields As Long
dmOrientation As Integer
dmPaperSize As Integer
dmPaperLength As Integer
dmPaperWidth As Integer
dmScale As Integer
dmCopies As Integer
dmDefaultSource As Integer
dmPrintQuality As Integer
dmColor As Integer
dmDuplex As Integer
dmResolution As Integer
dmTTOption As Integer
dmCollate As Integer
dmFormName As String * 16
dmPad As Long
dmBits As Long
dmPW As Long
dmPH As Long
dmDFI As Long
dmDFr As Long
End Type

Sub CheckCustomPage(rptName As String)

Dim DevString As str_DEVMODE

Dim DM As type_DEVMODE

Dim DevModeExtra As String

Dim rpt As Report

Dim response

' Opens report in Design view.
DoCmd.OpenReport rptName, acDesign
Set rpt = Reports(rptName)
If Not IsNull(rpt.PrtDevMode) Then

DevModeExtra = rpt.PrtDevMode	' Gets current DEVMODE structure.

DevString.RGB = DevModeExtra
LSet DM = DevString
If DM.dmPaperSize = 256 Then
' Display user-defined size.
response = MsgBox("The current Custom Page Size is " _

& DM.dmPaperWidth / 254 & " in wide by " & DM.dmPaperLength / 254 _

& " in long. Do you want to change the settings?", 4)

Else
' Currently not user-defined.
response = MsgBox("The report does not have a custom page. Do you want to define one?", 4)
End If
If response = 6 Then
' User wants to change settings.
' Initialize fields.
DM.dmFields = DM.dmFields Or DM_PAPERSIZE Or DM_PAPERLENGTH Or DM_PAPERWIDTH

DM.dmPaperSize = 256	' Set custom page.

' Prompt for length and width.

DM.dmPaperLength = InputBox("Please enter Page Length in inches") * 254
DM.dmPaperWidth = InputBox("Please enter Page Width in inches") * 254

LSet DevString = DM	' Update property.

Mid$(DevModeExtra, 1, 94) = DevString.RGB
rpt.PrtDevMode = DevModeExtra
End If

End If

End Sub

The following example shows how to change the orientation of the report. This example will switch the orientation from portrait to landscape or landscape to portrait depending on the report's current orientation.

Sub SwitchOrient(rptName As String)
Const DM_PORTRAIT = 1
Const DM_LANDSCAPE = 2
Dim DevString As str_DEVMODE
Dim DM As type_DEVMODE
Dim DevModeExtra As String
Dim rpt As Report

DoCmd.OpenReport rptName, acDesign	' Opens report in Design view.

Set rpt = Reports(rptName)
If Not IsNull(rpt.PrtDevMode) Then
DevModeExtra = rpt.PrtDevMode
DevString.RGB = DevModeExtra
LSet DM = DevString

DM.dmFields = DM.dmFields Or DM_ORIENTATION	' Initialize fields.

If DM.dmOrientation = DM_PORTRAIT Then
DM.dmOrientation = DM_LANDSCAPE
Else
DM.dmOrientation = DM_PORTRAIT
End If

LSet DevString = DM	' Update property.

Mid$(DevModeExtra, 1, 94) = DevString.RGB
rpt.PrtDevMode = DevModeExtra

End If

End Sub


PrtDevNames Property

You can use the PrtDevNames property to set or return information about the printer selected in the Print Setup dialog box.

Note   It is strongly recommended that you consult the Win32 Software Development Kit for complete documentation on the PrtDevMode, PrtDevNames, and PrtMip properties.

The PrtDevNames property applies only to tables and queries in Datasheet view and reports and forms.

Setting

The PrtDevNames property is a variable-length structure that mirrors the DEVNAMES structure defined in the Win32 Software Development Kit.

The PrtDevNames property uses the following members.

Member	Description

DriverOffset	Specifies the offset from the beginning of the structure to a Null-terminated string that specifies the filename (without an extension) of the device driver. This string is used to specify which printer is initially displayed in the Print Setup dialog box.

DeviceOffset	Specifies the offset from the beginning of the structure to the Null-terminated string that specifies the name of the device. This string can't be longer than 32 bytes (including the null character) and must be identical to the DeviceName member of the DEVMODE structure. You can determine the driver name and device name by looking at the [devices] section of the Win.ini file.

OutputOffset	Specifies the offset from the beginning of the structure to the Null-terminated string that specifies the MS-DOS device name for the physical output medium (output port); for example, "LPT1:".

Default	Specifies whether the strings specified in the DEVNAMES structure identify the default printer. Before the Print Setup dialog box is displayed, if Default is set to 1 and all of the values in the DEVNAMES structure match the current default printer, the selected printer is set to the default printer. Default is set to 1 if the current default printer has been selected.

Microsoft Access sets the PrtDevNames property when you make selections in the Printer section of the Print Setup dialog box. You can also set the property using Visual Basic.

Remarks

Microsoft Access uses the DEVNAMES structure to initialize the Print Setup dialog box. When the user chooses OK to close the dialog box, information about the selected printer is returned by the PrtDevNames property.


PrtMip Property

You can use the PrtMip property in Visual Basic to set or return the device mode information specified for a form, report, or module in the Print Setup dialog box.

Setting

The PrtMip property setting is a 28-byte structure that maps to settings for the Margins options and the Data Only option for a form, report, or module in the Print Setup dialog box. The structure also maps to the options displayed after you choose the More button in the Print Setup dialog box. (The More button is enabled only for a form in Form view or a report.)

The PrtMip property uses the following members.

Member	Description
LeftMargin, RightMargin, TopMargin, BottomMargin	An Integer that specifies the distance between the edge of the page and the item to be printed in twips.
DataOnly	An Integer that specifies the elements to be printed. When True (-1), prints only the data in a table or query in Datasheet view, form, or report, and suppresses labels, control borders, gridlines, and display graphics such as lines and boxes. When False (0), prints data, labels, and graphics.
ItemsAcross	An Integer that specifies the number of columns across for multiple-column reports or labels.
RowSpacing	An Integer that specifies the horizontal space between detail sections in units of 1/20 of a point.
ColumnSpacing	An Integer that specifies the vertical space between detail sections in twips.
DefaultSize	An Integer. When True, uses the size of the detail section in Design view. When False, uses the values specified by the ItemSizeWidth and ItemSizeHeight members.
ItemSizeWidth	An Integer that specifies the width of the detail section in twips.
ItemSizeHeight	An Integer that specifies the height of the detail section twips.
ItemLayout	An Integer that specifies horizontal (1953) or vertical (1954) layout of columns.
FastPrint	Reserved
Datasheet	Reserved
The PrtMip property setting is read/write in Design view and read-only in other views.


PrtMip Property Example

The following PrtMip property example demonstrates how to setup the report with 2 horizontal columns.

Type str_PRTMIP
RGB As String * 56
End Type

Type type_PRTMIP
xLeftMargin As Integer
yTopMargin As Integer
xRightMargin As Integer
yBotMargin As Integer
fDataOnly As Integer
xWidth As Integer
yHeight As Integer
fDefaultSize As Integer
cxColumns As Integer
yColumnSpacing As Integer
xRowSpacing As Integer
rItemLayout As Integer
fFastPrint As Integer
fDatasheet As Integer
End Type

Sub PrtMipCols(rptName As String)
Dim PrtMipString As str_PRTMIP
Dim PM As type_PRTMIP
Dim rpt As Report
Const PM_HORIZONTALCOLS = 1953
Const PM_VERTICALCOLS = 1954
DoCmd.OpenReport rptName, acDesign	' Open report in Design view.

Set rpt = Reports(rptName)
PrtMipString.RGB = rpt.PrtMip
LSet PM = PrtMipString
PM.cxColumns = 2	' Create two columns.

PM.xRowSpacing = 0.25 * 1440	' Set 0.25 inch between rows.

PM.yColumnSpacing = 0.5 * 1440	' Set 0.5 inch between columns.

PM.rItemLayout = PM_HORIZONTALCOLS

LSet PrtMipString = PM	' Update property.

rpt.PrtMip = PrtMipString.RGB

End Sub

The next PrtMip property example shows how to set all margins to 1 inch.

Sub SetMarginsToDefault(rptName As String)
Dim PrtMipString As str_PRTMIP
Dim PM As type_PRTMIP
Dim rpt As Report
DoCmd.OpenReport rptName, acDesign	' Open report in Design view.

Set rpt = Reports(rptName)
PrtMipString.RGB = rpt.PrtMip
LSet PM = PrtMipString
PM.xLeftMargin = 1 * 1440	' Set margins.

PM.yTopMargin = 1 * 1440
PM.xRightMargin = 1 * 1440
PM.yBotMargin = 1 * 1440
LSet PrtMipString = PM	' Update property.

rpt.PrtMip = PrtMipString.RGB

End Sub


DestConnectStr, DestinationDB, DestinationTable Properties

You can use these properties with make-table or append queries only.

DestinationDB [image] You can use this property to specify the type of application used to create an external database.

DestConnectStr [image] You can use this property to specify the connection string for the name of the database that will contain the new table (for make-table queries) or the name of the database that contains the table to which data will be appended (for append queries).

DestinationTable [image] You can use this property to specify the name of the new table or the name of the table to be appended to that will hold the results of the query.

Note   The DestConnectStr, DestinationDB, and DestinationTable properties apply only to make-table and append queries.

Setting

You set the DestConnectStr, DestinationDB, and DestinationTable properties using a string expression.

The default setting for DestinationDB property is "(current)", which refers to the currently active database.

You can set these properties in the query property sheet, or in SQL view of the Query window.

In the SQL statement for an append query, the table name in the INSERT INTO statement corresponds to the DestinationTable property setting. The IN clause corresponds to the DestinationDB and DestConnectStr property settings.

In the SQL statement for a make-table query, the table name in the INTO clause corresponds to the DestinationTable property setting. The IN clause corresponds to the DestinationDB and DestConnectStr property settings.

Note   Microsoft Access sets these properties automatically based on the information you enter in the query property sheet or in SQL view of the Query window.

Remarks

When you choose Make Table or Append on the Query menu, Microsoft Access prompts you for the information needed to set these properties. Microsoft Access uses the value you enter in the Table Name box to set the DestinationTable property, and it uses the information you type in the File Name box to set the DestConnectStr and DestinationDB properties.

To use the property sheet to specify a table in a Microsoft Access database, enter the name of the table in the Destination Table box (for example, Clients). In the Destination DB box, enter the path and database name without the filename extension (for example, C:\Accounts\Customers). Microsoft Access adds the extension automatically. You don't need to set the DestConnectStr property.

To specify a table in a database created by a different product, such as Paradox, enter the name of the table in the Destination Table box. In the Destination DB box, enter the path (for example, C:\Paradoxdata). In the Dest Connect Str box, enter the specifier for the database type (for example, Paradox 3.5). For a list of specifiers, see the Connect property.

To specify an Open Database Connectivity (ODBC) database, enter the name of the database in the Dest Connect Str box along with additional information, such as a logon identification (ID) and password, as required by the product. For example, you might use the following setting for a Microsoft SQL Server database.

ODBC;DSN=salessrv;UID=jace;PWD=password;DATABASE=sales;

For more information about ODBC drivers, such as Microsoft SQL Server, see the online Help provided with the driver.

You don't need to set the DestinationDB property for ODBC databases.


DestConnectStr, DestinationDB, DestinationTable Properties Example

The following example appends the records in the Customers table to the Clients table in a Microsoft Access database named Clients in the C:\Data directory. You can enter this SQL statement in SQL view of the Query window.

INSERT INTO Clients IN 'C:\Data\Clients.mdb'
SELECT DISTINCTROW Customers.[CompanyName], Customers.Phone
FROM Customers;

The next example creates a new table named Contacts in a Paradox version 3.5 database in the C:\Paradoxdata directory.

SELECT DISTINCTROW Customers.[CompanyName], Customers.Phone
INTO Contacts IN 'C:\Paradoxdata	' [Paradox 3.5]
FROM Customers;


 LogMessages Property

You can use the LogMessages property in an SQL pass-through query to specify whether messages returned from a SQL database are stored in a messages table in the current Microsoft Access database.

Note   The LogMessages property applies only to pass-through queries.

Setting

The LogMessages property uses the following settings.

Setting	Description	Visual Basic
Yes	Microsoft Access stores messages returned from the SQL database in a messages table.	True (-1)
No	(Default) Microsoft Access doesn't store messages returned from the SQL database.	False (0)
You can set this property using the query property sheet or Visual Basic.

Remarks

The name of the messages table where the returned messages are stored is username - nn, where username is the logon name of the user running the pass-through query, and nn is an Integer that increases in increments of 1, starting at 00. For example, if user JoanW sets the LogMessages property to Yes and receives messages from an SQL database, the messages table will be named JoanW - 00. If JoanW receives messages in another Microsoft Access session (and the first table hasn't been deleted), a new table named JoanW - 01 is created.

Note   Error messages from the SQL server aren't stored in the messages table.


ODBCConnectStr Property

You can use the ODBCConnectStr property in an SQL pass-through query to specify the Open Database Connectivity (ODBC) connection string for the query.

Note   The ODBCConnectStr property applies only to pass-through queries.

Setting

Enter the ODBC connection string that defines the connection to the SQL database you want to use.

You can set this property using the query property sheet or Visual Basic.

You can also use the ODBC Connection String Builder to create the ODBC connection string for this property. This builder establishes a connection to the SQL database server and then ends the connection after the ODBC connection string is created.

Remarks

The default setting for this property is the string "ODBC;", which Microsoft Access restores if you delete an existing setting. When the ODBCConnectStr property is set to "ODBC;", Microsoft Access will prompt you for a connection string whenever the query is used but won't store the connect string. You must enter a connection string in the ODBCConnectStr property box if you want Microsoft Access to store the connection string.

Tip   If you know the full connection string for the SQL database, enter it in the ODBCConnectStr property box. This way you will avoid the need to enter the connection string in the ODBC connection dialog box each time you use the query.

The connection string is different for different types of ODBC data sources. For example, to connect to the Human Resources data source on the HRSRVR server (a Microsoft SQL Server) using the logon identification (ID) Smith and the password Sesame, you can use the following connection string.

ODBC;DSN=Human Resources;SERVER=HRSRVR;UID=Smith;PWD=Sesame


ODBCTimeout Property (Microsoft Access)

You can use the ODBCTimeout property to specify the number of seconds Microsoft Access waits before a time-out error occurs when a query is run on an Open Database Connectivity (ODBC) database.

Setting

The ODBCTimeout property is an Integer value representing the number of seconds Microsoft Access waits. The default is 60 seconds. When this property is set to 0, no timeout occurs.

You can set this property in the property sheet in the Query window or Visual Basic.

Remarks

When you're using an ODBC database, such as an Microsoft SQL Server, there may be delays due to network traffic or heavy use of the ODBC server. The ODBCTimeout property lets you specify how long Microsoft Access waits for a network connection before a time-out error occurs.

When the ODBCTimeout property is set to zero, no time-out errors occur.


SourceConnectStr, SourceDatabase Properties

You can use these properties to access external data when you can't link the external tables to your database.

SourceConnectStr [image] You can use this property to specify the name of the application used to create an external database.

SourceDatabase [image] You can use this property to specify the external database in which the input tables or queries for a query reside.

Note   The SourceConnectStr and SourceDatabase properties apply to all queries except data-definition, pass-through, and union queries.

Setting

You use a string expression to set the value of the SourceConnectStr and SourceDatabase properties.

You can set these properties in the query property sheet or in SQL view of the Query window. In the SQL statement, the properties correspond to the IN clause.

Note   If you are accessing multiple database sources, use the Source property

Remarks

You must use the SourceConnectStr and SourceDatabase properties to access tables from external databases created in applications that don't use linked tables.

The following are examples of these property settings if an application that doesn't use linked tables accesses the data from databases created by Microsoft Access and other database products:

For a Microsoft Access database, the SourceDatabase property setting is the path and database name (for example, C:\Accounts\Customers). Microsoft Access adds the filename extension automatically. The SourceConnectStr property doesn't have a value for a Microsoft Access database.

For a database created by a product such as Paradox, the SourceDatabase property setting is the path (for example, C:\Paradoxdata). The SourceConnectStr property setting is the specifier for the database type (for example, Paradox 3.5;). For a list of specifiers, see the Connect property.

The following example uses dBASE IV tables in the C:\Dbdata directory as the source of data for the query.

SELECT DISTINCTROW Customers.[Company Name], Orders.[Order ID], _

Orders.[Order Date] FROM Customers INNER JOIN Orders ON _

Customers.[Customer ID] = Orders.[Customer ID] IN 'C:\Dbdata'[dBASE IV;];

For an Open Database Connectivity (ODBC) database, the SourceConnectStr property setting is the name of the source database and any additional information required by the product, such as a logon identification (ID) and password. For example, for a Microsoft SQL Server database, the setting might be:

ODBC;DSN=salessrv;UID=jace;PWD=password;DATABASE=sales;

The SourceDatabase property doesn't have a value for an ODBC database.


UniqueRecords Property

You can use the UniqueRecords property to specify whether to return only unique records based on all fields in the underlying data source, not just those fields present in the query itself.

Note   The UniqueRecords property applies only to crosstab, data-definition, pass-through, and union queries.

Setting

The UniqueRecords property uses the following settings.

Setting	Description

Yes	(Default) Doesn't return duplicate records.

No	Returns duplicate records.

You can set the UniqueRecords property in the query property sheet or SQL view of the Query window.

Note   You set this property when you create a new query using an SQL statement. The DISTINCTROW predicate corresponds to the UniqueRecords property setting. The DISTINCT predicate corresponds to the UniqueValues property setting.

Remarks

You can use the UniqueRecords property when you want to omit data based on entire duplicate records, not just duplicate fields. Microsoft Access considers a record to be unique as long as the value in one field in the record differs from the value in the same field in another record.

The UniqueRecords property has an effect only when you use more than one table in the query and select fields from the tables used in the query. The UniqueRecords property is ignored if the query includes only one table.

The UniqueRecords and UniqueValues properties are related in that only one of them can be set to Yes at a time. When you set UniqueRecords to Yes, for example, Microsoft Access automatically sets UniqueValues to No. You can, however, set both of them to No. When both properties are set to No, all records are returned.


UniqueRecords Property Example

The query in this example returns a list of customers from the Customers table who have at least one order in the Orders table.

Customers Table

Customer name	Customer ID

Bon app'	1

Simons bistro	2

Reggiani Caseifici	3

Bon appetit'	4

Orders Table

Customer ID	Order ID

1	10

2	11

2	12

4	13

4	14

This SQL statement returns the customer names in the following table.

SELECT DISTINCTROW Customers.[CompanyName]
FROM Customers INNER JOIN Orders ON
Customers.[CustomerID] = Orders.[CustomerID];

Customers returned	Customer ID

Bon app'	1

Simons bistro	2

Bon appetit'	3


UniqueValues Property

You can use the UniqueValues property when you want to omit records that contain duplicate data in the fields displayed in Datasheet view. For example, if a query's output includes more than one field, the combination of values from all fields must be unique for a given record to be included in the results.

Note   The UniqueValues property applies only to all queries except append, make-table, and select queries.

Setting

The UniqueValues property uses the following settings.

Setting	Description

Yes	Displays only the records in which the values of all fields displayed in Datasheet view are unique.

No	(Default) Displays all records.

You can set the UniqueValues property in the query property sheet or SQL view of the Query window.

Note   You can set this property when you create a new query using an SQL statement. The DISTINCT predicate corresponds to the UniqueValues property setting. The DISTINCTROW predicate corresponds to the UniqueRecords property setting.

Remarks

When you set the UniqueValues property to Yes, the results of the query aren't updatable and won't reflect subsequent changes made by other users.

The UniqueValues and UniqueRecords properties are related in that only one of them can be set to Yes at a time. When you set the UniqueValues property to Yes, for example, Microsoft Access automatically sets the UniqueRecords property to No. You can, however, set both of them to No. When both properties are set to No, all records are returned.

Tip   If you want to count the number of instances of a value in a field, create a totals query.


UniqueValues Property Example

The SELECT statement in this example returns a list of the countries in which there are customers. Because there may be many customers in each country, many records could have the same country in the Customers table. However, each country is represented only once in the query results.

This example uses the Customers table, which contains the following data.

Country	Company name

Brazil	Familia Arquibaldo

Brazil	Gourmet Lanchonetes

Brazil	Hanari Carnes

France	Du monde entier

France	Folies gourmandes

Ireland	Hungry Owl All-Night Grocers

Germany	Frankenversand

This SQL statement returns the countries in the following table.

SELECT DISTINCT Customers.[Country]
FROM Customers;

Countries returned

Brazil

France

Ireland

Germany


ActiveControl Property

You can use the ActiveControl property together with the Screen object to identify or refer to the control that has the focus.

Setting

This property setting contains the control object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveControl property to refer to the control that has the focus at runtime together with one of its properties or methods. The following example assigns the name of the control with the focus to the strControlName variable.

Dim CurrentControl As Control

Dim strControlName As String

Set CurrentControl = Screen.ActiveControl

strControlName = CurrentControl.Name

If no control has the focus when you use the ActiveControl property, or if all of the active form's controls are hidden or disabled, an error occurs.


ActiveControl Property Example

The following code assigns the active control to the CurrentControl variable and then takes different actions depending on the value of the control's Name property.

Dim CurrentControl As Control

Set CurrentControl = Screen.ActiveControl

If CurrentControl.Name = "txtCustomerID" Then

.	' Do this.

.

.

ElseIf CurrentControl.Name = "btnCustomerDetails" Then

.	' Do this.

.

.

End If


ActiveForm Property

You can use the ActiveForm property together with the Screen object to identify or refer to the form that has the focus.

Setting

This property setting contains the form object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveForm property to refer to an active form together with one of its properties or methods. The following example displays the Name property setting of the active form.

Dim CurrentForm As Form

Set CurrentForm = Screen.ActiveForm

MsgBox "Current form is " & CurrentForm.Name

If a subform has the focus, ActiveForm refers to the main form. If no form or subform has the focus when you use the ActiveForm property, an error occurs.


ActiveReport Property

You can use the ActiveReport property together with the Screen object to identify or refer to the report that has the focus.

Setting

This property setting contains the report object that has the focus at run time.

This property is available only in Visual Basic and is read-only in all views.

Remarks

You can use the ActiveReport property to refer to an active report together with one of its properties or methods. The following example displays the Name property setting of the active report.

Dim CurrentReport As Report

Set CurrentReport = Screen.ActiveReport

MsgBox "Current report is " & CurrentReport.Name

If no report has the focus when you use the ActiveReport property, an error occurs.


Bookmark Property (Microsoft Access)

You can use the Bookmark property with forms to set a bookmark that uniquely identifies a particular record in the form's underlying table, query, or SQL statement.

Setting

The Bookmark property contains a string expression created by Microsoft Access.

You can access this property using Visual Basic or a macro.

Note   You get or set the form's Bookmark property separately from the underlying table or query data access Bookmark property.

Remarks

When a bound form is opened in Form view, each record is assigned a unique bookmark. In Visual Basic, you can save the bookmark for the current record by assigning the value of the form's Bookmark property to a string variable. To return to a saved record after moving to a different record, set the form's Bookmark property to the value of the saved string variable.

Note   Bookmarks are not saved with the records they represent. They are re-created by Microsoft Access each time a bound form is opened.

There is no limit to the number of bookmarks you can save if each is saved with a unique string variable.

The Bookmark property is only available for the form's current record. To save a bookmark for a record other than the current record, move to the desired record and assign the value of the Bookmark property with a string variable that identifies this record.

You can use bookmarks in any form that is based entirely on Microsoft Access tables. However, other database products may not support bookmarks. For example, you can't use bookmarks in a form based on a linked table that has no primary index.

Requerying a form invalidates any bookmarks set on records in the form. However, clicking Refresh on the Records menu doesn't affect bookmarks.

Since Microsoft Access creates a unique bookmark for each record in a form's recordset when a form is opened, a form's bookmark will not work on another recordset, even when the two recordsets are based on the same table, query or SQL statement. For example, suppose you open a form bound to the Customers table. If you then open the Customers table using Visual Basic and use the Seek method to locate a specific record in the table, you can't set the form's Bookmark property to the current table record. To perform this kind of operation you use the form's RecordsetClone property.

A trappable error occurs if you save the Bookmark property with a string variable and then try to return to that record after the record has been deleted.

The value of the Bookmark property isn't the same as a record number.


Bookmark Property Example

The following example determines the Bookmark property for the current record in the Customers form.

Dim strLocation As String

strLocation = Forms![Customers].Bookmark


CurrentObjectType, CurrentObjectName Properties

You can use the CurrentObjectType and CurrentObjectName properties together with the Application object to determine the type of the active database object (table, query, form, report, macro, or module) and the name of the active database object.

Setting

The CurrentObjectType property is set by Microsoft Access to one of the following Microsoft Access intrinsic constants.

Setting	Description

acTable	The active object is a table.

acQuery	The active object is a query.

acForm	The active object is a form.

acReport	The active object is a report.

acMacro	The active object is a macro.

acModule	The active object is a module.

The CurrentObjectName property is set by Microsoft Access to a string expression containing the name of the active object.

These property settings are available only in Visual Basic and are read-only in all views.

Remarks

The following conditions determine which object is considered the active object:

If the user chooses the property sheet, toolbar, menu, palette, or the field list of an object, the CurrentObjectType and CurrentObjectName properties return the type and name of the underlying object.

If the user chooses a pop-up form, the CurrentObjectType and CurrentObjectName properties refer to the pop-up form itself, not the form from which it was opened.

If the active object is the Database window, the CurrentObjectType and CurrentObjectName properties return the item selected in the Database window.

If no object is selected, the CurrentObjectType property returns True (-1), and the CurrentObjectName property returns a zero-length string (" ").

If the current state is ambiguous (the active object isn't a table, query, form, report, macro, or module) [image] for example, if a dialog box has the focus [image] the CurrentObjectType property returns True, and the CurrentObjectName property returns the dialog box name.

You can use these properties with the SysCmd function to determine the active object and its state (for example, if the object is open, new, or has been changed but not saved).


CurrentObjectType, CurrentObjectName Properties Example

The following example uses the CurrentObjectType and CurrentObjectName properties with the SysCmd function to determine if the active object is the Products form and if this form is open and has been changed but not saved. If these conditions are true, the form is saved and then closed.

Sub CheckProducts()

Dim intState As Integer

Dim intCurrentType As Integer

Dim strCurrentName As String

intCurrentType = Application.CurrentObjectType

strCurrentName = Application.CurrentObjectName

If intCurrentType = acForm And strCurrentName = "Products" Then

intState = SysCmd(acSysCmdGetObjectState, intCurrentType, strCurrentName)

' Products form changed but not saved.

If intState = acObjStateDirty + acObjStateOpen Then

' Close Products form and save changes.

DoCmd.Close intCurrentType, strCurrentName, acYes

End If

End If

End Sub


Me Property

You can use the Me property in Visual Basic to refer to a form or report, or the form or report associated with a subform or subreport, where Visual Basic code is currently running.

Setting

The Me property is available only in Visual Basic and is read-only in all views.

Remarks

In most cases, the form or report referred to by the Me property is the same form or report referred to by the ActiveForm or ActiveReport properties of the Screen object. However, these properties refer to the form or report with the focus, whereas the Me property always refers to the form or report in which code is running. For example, a Timer event can occur in a form that doesn't have the focus. When that happens, the code Screen.ActiveForm refers to the form with the focus, and the Me property refers to the form in which the Timer event occurred. Therefore, when creating generic procedures that operate on the current form, the preferred method is to pass the form to the procedure using the Me property rather than the ActiveForm property.


Me Property Example

The following example shows how to change the caption of the Customers form to the current company name whenever a new record is displayed. The form's Current event procedure calls the ChangeCaption subroutine and passes it the Me property to specify the active form. The ChangeCaption procedure changes the caption of the form. Because the ChangeCaption procedure changes the caption of the active form (and not a specific form), it can be called from other procedures in an application.

Sub Form_Current()

ChangeCaption Me	' Pass current form name as argument.

End Sub

Sub ChangeCaption(frmCurrentForm As Form)

frmCurrentForm![CompanyName].SetFocus	' Move focus to Customer Name text box.

frmCurrentForm.Caption = frmCurrentForm![CompanyName].Text	' Change caption.

End Sub


Module Property

You can use the Module property to specify a form module or report module.

Setting

The Module property is available only in Visual Basic and is read-only in all views.

Remarks

You can use this property only with the InsertText method to specify the module you want to insert code into.


Module Property Example

The following example uses the Module property to insert the Beep method into the form Open event.

Dim strFormOpenCode As String

strFormOpenCode = "Sub Form_Open(Cancel As Integer)" & vbCrLf & "Beep" & strCRLF & "End Sub"

Forms![MyForm].Module.InsertText strFormOpenCode


RecordsetClone Property

You can use the RecordsetClone property to refer to a form's Recordset object specified by the form's RecordSource property.

Setting

The RecordsetClone property setting is a copy of the underlying query or table specified by the form's RecordSource property. If a form is based on a query, for example, referring to the RecordsetClone property is the equivalent of cloning a Recordset object using the same query. If you then apply a filter to the form, the Recordset object reflects the filtering.

The RecordsetClone property is available only in Visual Basic and is read-only in all views.

Remarks

You use the RecordsetClone property to navigate or operate on a form's records independent of the form itself. For example, you can use the RecordsetClone property when you want to use a method, such as the FindFirst method, that can't be used with forms. The RecordsetClone property provides access to all the methods and properties that apply to a Recordset object.

When a new Recordset object is opened, its first record is the current record. If you use one of the Find or Move methods to make any record in the Recordset object current, you must synchronize the current record in the Recordset object with the form's current record by assigning the value of the form's Bookmark property to a string variable, and then assign the string variable to the data access Bookmark property of the Recordset object.

You can use the RecordCount property to count the number of records in a Recordset object. The following example shows how you can combine the RecordCount property and the RecordsetClone property to count the records in a form.

Forms!Orders.RecordsetClone.MoveLast

Msg = "My form contains " & Forms!Orders.RecordsetClone.RecordCount

Msg = Msg & " records.", vbInformation, "Record Count"

MsgBox Msg

Note   If you close the form or if you change the form's RecordSource property, the Recordset object is no longer valid. If you subsequently refer to the Recordset object or to previously saved bookmarks in the form or the Recordset object, an error will occur.


RecordsetClone Property Example

The following example uses the RecordsetClone property to create a Recordset object from the Orders form and then prints the names of the fields in the Debug window.

Sub Print_Field_Names()

Dim rs As Recordset, intI As Integer

Set rs = Me.RecordsetClone

For intI = 0 To rs.Fields.Count - 1

Debug.Print rs.Fields(intI).Name	' Print field names.

Next intI

End Sub

The next example uses the RecordsetClone property and the Recordset object to synchronize a recordset's record with the form's current record. When a company name is selected from a combo box, the FindFirst method is used to locate the record for that company and the Recordset object's Bookmark property is assigned to the form's Bookmark property causing the form to display the found record.

Sub CompanyName_AfterUpdate()

Dim rs As Recordset

Dim strSearchName As String

Set rs = Me.RecordsetClone

strSearchName = Me!CompanyName

rs.FindFirst "[CompanyName] = '" & strSearchName & "'"

If rs.NoMatch Then

MsgBox "Record not found"

Else

Me.Bookmark = rs.Bookmark

End If

rs.Close

End Sub


Dynaset Property

You can use the Dynaset property to obtain a result set for a form's underlying records.

Note   The Dynaset property is included in this version of Microsoft Access only for compatibility with previous versions. It is recommended that you use the RecordsetClone property instead.

Setting

The Dynaset property is available only in Visual Basic and is read-only in all views.

Remarks

The Dynaset property refers to the same underlying query or data as the form. If a form is based on a query, for example, referring to the Dynaset property is the equivalent of cloning a result set with the same query. If you then apply a filter to the form, the Dynaset property reflects the filtering.

Unlike its form, the result set initially has no current record. To make the same record current in the result set, assign the value of the form's Bookmark property to a string variable, and then set the result set's Bookmark property to that variable. You can also use one of the Find or Move methods to make any record in the result set current.

Tip   You can make the form's current record the same as the result set's by setting the form's Bookmark property to the result set's Bookmark property.

Use the Dynaset property when you want to apply a method that can't be used with forms, such as the FindFirst method. The Dynaset property provides access to all the methods and properties that you can use with a result set.

You can use the RecordCount property to count the number of records in a result set. The following example shows how you can combine the RecordCount property with the Dynaset property to count the records in a form.

Forms![Orders].Dynaset.MoveLast

MsgBox "My form contains " & Forms![Orders].Dynaset.RecordCount _

& " records.", , "Record Count"

Note   If you close the form or if you change the form's set of underlying records, the result set is no longer valid. Subsequently, if you refer to the result set or to previously saved bookmarks in the form or the result set, an error occurs.


ColumnHidden Property

You can use the ColumnHidden property to show or hide a specified column in Datasheet view. For example, you might want to hide a CustomerAddress field that's too wide so you can view the CustomerName and PhoneNumber fields.

Note   The ColumnHidden property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

The ColumnHidden property uses the following settings.

Setting	Description	Visual Basic
Hide	The column is hidden.	True (-1)
Unhide	(Default) The column is visible.	False (0)
You can set this property by clicking Hide Columns or Unhide Columns on the Format menu in Datasheet view.

You can also set this property in Visual Basic using a Long value.

To set or change this property for a table or query using Visual Basic, you must use a field's Properties collection. For details on using the Properties collection, see Property Object, Properties Collection Summary.

Note   The ColumnHidden property is not available in form Design view.

Remarks

Hiding a column in Datasheet view does not hide fields from the same column in Form view. Similarly, setting a control's Visible property to False in Form view doesn't hide the corresponding column in Datasheet view.

You can display a field in a query even though the column for the field is hidden in table Datasheet view.

You can use values from a hidden column as the criteria for a filter even though the column remains hidden after the filter is applied.

You can't use the Copy, Paste, Find, and Replace commands on the Edit menu to affect hidden columns.

Setting a field's ColumnWidth property to 0, or resizing the field to a zero width in Datasheet view, causes Microsoft Access to set the corresponding ColumnHidden property to True. Unhiding a column restores the ColumnWidth property to the value it had before the field was hidden.


ColumnHidden Property Example

The following example hides the ProductID field in Datasheet view of the Products form.

Forms![Products]![ProductID].ColumnHidden = -1

The next example also hides the ProductID field in Datasheet view of the Products table. To set the ColumnHidden property, the example uses the ShowColumn and SetFieldProperty procedures, which are in the database's standard module.

Dim db As Database

Set db = CurrentDb

ShowColumn db.TableDefs![Products].Fields![ProductID], False

Sub ShowColumn (FieldObj As Field, Show As Integer)

' Set ColumnHidden property.

SetFieldProperty FieldObj, "ColumnHidden", dbLong, Not Show

End Sub

Sub SetFieldProperty (fldField As Field, strPropertyName As String, _

intPropertyType As Integer, varPropertyValue As Variant)

' Set field property without producing nonrecoverable run-time error.

Const conErrPropertyNotFound = 3270

Dim proProperty As Property

On Error Resume Next	' Don't trap errors.

fldField.Properties(strPropertyName) = varPropertyValue

If Err <> 0 Then	' Error occurred when value set.

If Err <> conErrPropertyNotFound Then

On Error GoTo 0

MsgBox "Couldn't set property '" & strPropertyName _

& "' on field '" & fldField.name & "'", 48, "SetFieldProperty"

Else

On Error GoTo 0

Set proProperty = fldField.CreateProperty(strPropertyName, _

intPropertyType, varPropertyValue)

fldField.Properties.Append proProperty

End If

End If

End Sub


ColumnOrder Property

You can use the ColumnOrder property to specify the order of the columns in Datasheet view.

Note	The ColumnOrder property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You set this property by selecting a column in Datasheet view and dragging it to a new position.

You set the ColumnOrder property in Visual Basic using a Long value.

To set or change this property for a table or query using Visual Basic, you must use a field's Properties collection. For details, see Property Object, Properties Collection Summary.

Note   The ColumnOrder property is not available in form Design view.

Remarks

In Datasheet view, a field's ColumnOrder property setting is determined by the field's position. For example, the field in the leftmost column in Datasheet view has a ColumnOrder property setting of 1, the next field has a setting of 2, and so on. Changing a field's ColumnOrder property resets the ColumnOrder property for that field and every field to the left of its original position in Datasheet view.

In other views, the ColumnOrder property setting is 0 unless you explicitly change the order of one or more fields in Datasheet view (either by dragging the fields to new positions or by changing their ColumnOrder property settings). Fields to the right of the moved field's new position will have a ColumnOrder property setting of 0 in views other than Datasheet view.

The order of the fields in Datasheet view doesn't affect the order of the fields in table Design view or Form view.


ColumnOrder Property Example

The following example displays the ProductName and QuantityPerUnit fields in the first two columns in Datasheet view of the Products form.

Forms![Products]![ProductName].ColumnOrder = 1

Forms![Products]![QuantityPerUnit].ColumnOrder = 2

The next example displays the ProductName and QuantityPerUnit fields in the first two columns of the Products table in Datasheet view. To set the ColumnOrder property, the example uses the SetFieldProperty procedure.

Dim db As Database, tdProducts As TableDef

Set db = CurrentDb

Set tdProducts = db![Products]

SetFieldProperty tdProducts![ProductName], "ColumnOrder", dbLong, 2

SetFieldProperty tdProducts![QuantityPerUnit], "ColumnOrder", dbLong, 3

Sub SetFieldProperty (fldField As Field, strPropertyName As String, _

intPropertyType As Integer, varPropertyValue As Variant)

' Set field property without producing nonrecoverable run-time error.

Const conErrPropertyNotFound = 3270

Dim proProperty As Property

On Error Resume Next	' Don't trap errors.

fldField.Properties(strPropertyName) = varPropertyValue

If Err <> 0 Then	' Error occurred when value set.

If Err <> conErrPropertyNotFound Then

On Error GoTo 0

MsgBox "Couldn't set property '" & strPropertyName _

& "' on field '" & fldField.name & "'", 48, "SetFieldProperty"

Else

On Error GoTo 0

Set proProperty = fldField.CreateProperty(strPropertyName, _

intPropertyType, varPropertyValue)

fldField.Properties.Append proProperty

End If

End If

End Sub


AutoCenter Property

You can use the AutoCenter property to specify whether a form will be centered automatically in the application window when the form is opened.

Setting

The AutoCenter property uses the following settings.

Setting	Description	Visual Basic
Yes	The form will be centered automatically on opening.	True (-1)
No	(Default) The form won't be centered automatically on opening.	False (0)
You can set this property in the form's property sheet, a macro, or Visual Basic.

You can set this property only in Design view.

Remarks

Depending on the size and placement of the application window, forms can appear off to one side of the application window, hiding part of the form. Centering the form automatically when it's opened makes it easier to view and use.


CurrentSectionLeft, CurrentSectionTop Properties

You can use these properties to determine the distance in twips from the top edge and left side of the current section to the top edge and left side of the form.

Setting

CurrentSectionLeft [image] An Integer value that represents the distance from the left side of the current section to the left edge of the form.

CurrentSectionTop [image] An Integer value that represents the distance from the top edge of the current section from the top edge of the form.

These property settings are read-only and are available only in a macro or Visual Basic.

Remarks

The CurrentSectionLeft and CurrentSectionTop property settings change whenever a user scrolls through a form.

In single form view, if the user scrolls above the upper-left corner of the section or to the right of the left edge of the form, the property settings are negative values. If a section isn't visible in the Form window, these properties are set to Null.

In continuous form view, if a section isn’t visible the CurrentSectionTop property is equal to the InsideHeight property of the form.

These properties are useful for finding the position of detail sections displayed in Form view as continuous forms. Each detail section has a different CurrentSectionTop property setting, depending on the section's position on the form.


CurrentSectionLeft, CurrentSectionTop Property Example
CurrentSectionLeft, CurrentSectionTop Properties Example

The following example displays the CurrentSectionLeft and CurrentSectionTop property settings for a control on a continuous form. Whenever the user moves to a new record, the property settings for the current section are displayed in the lblStatus label in the form's header.

Private Sub Form_Current()

Dim intCurTop As Integer, intCurLeft As Integer

intCurTop = Me.CurrentSectionTop

intCurLeft = Me.CurrentSectionLeft

Me!lblStatus.Caption = intCurLeft & " , " & intCurTop

End Sub


WindowHeight, WindowWidth Properties

You can use these properties to return the height and width of a form in twips.

Setting

WindowHeight property settings are Integer values.

WindowWidth property settings are Integer values.

These property settings are read-only and are available only in a macro or Visual Basic.

Remarks

The WindowHeight property is measured from the upper-left corner of the form to its lower-left corner. The WindowWidth property is measured from the upper left corner of the form to its upper-right corner.


Dirty Property

You can use the Dirty property to determine whether the current record has been modified since it was last saved. For example, you may want to ask the user whether changes to a record were intended and, if not, allow the user to move to the next record without saving the changes.

Setting

The Dirty property has the following settings.

Setting	Description	Visual Basic
True	The current record has been changed.	True (-1)
False	The current record has not been changed.	False (0)
This property is available only in Form view and Datasheet view.

This property is read-only and available only in a macro or using Visual Basic.

Remarks

When a record is saved, the Dirty property is automatically set to False. When a user makes changes to a record, the property is set to True.


Dirty Property Example

The following example enables the btnUndo button when data is changed. The UndoEdits( ) subroutine is called from the AfterUpdate event of text box controls. Clicking the enabled btnUndo button restores the original value of the control using the OldValue property.

Sub UndoEdits()

If Me.Dirty Then

Me!btnUndo.Enabled = True	  ' Enable button.

Else

Me!btnUndo.Enabled = False	  ' Disable button.

End If

End Sub

Sub btnUndo_Click()

Dim intNumControls As Integer, i As Integer

Dim C As Control

intNumControls = Forms!EditForm.Count

For i = 0 to intNumControls - 1	  ' For each control.

Set C = Forms!EditForm(i)

If TypeOf C Is TextBox Then	  ' If control is TextBox.

C.Value = C.OldValue	  ' Restore Old Value.

End If

Next i

End Sub


FieldName Property

You can use the FieldName property to specify the name of a field within a table. For example, you can specify "Last Name" for a field that stores employees' last names within the Employees table.

Setting

Enter a field name, following Microsoft Access object naming rules. The name can't duplicate any other field name in the table.

Note   Avoid specifying a name for a field that could cause a conflict with built-in Microsoft Access function or property names, such as the Name property.

You can set this property in the upper portion of table Design view or using Visual Basic.

In Visual Basic, use the Data Access Object's Name property to read and set a table's field name.

Remarks

Microsoft Access identifies a field by its field name. Once you have specified a field name in table Design view, you can use that name in expressions, Visual Basic procedures, and SQL statements.


Unique Property

You can use the Unique property to specify that an index enforces uniqueness of the data in the table's key index.

Setting

The Unique property uses the following settings.

Setting	Description	Visual Basic
Yes	The index is a key (unique) index.	True (-1)
No	The index is a non-key index.	False (0)
You can set this property in the Indexes window of table Design view or in Visual Basic.

Note   To access the Unique property of an index using Visual Basic, use the Data Access Object's Unique property.

Remarks

A key index helps to optimize finding records. It consists of one or more fields that uniquely arrange all records in a table in a predefined order. If the index consists of one field, values in that field must be unique. If the index consists of more than one field, duplicate values can occur in each field, but each combination of values from all the indexed fields must be unique. A non-key index has fields with values that are not necessarily unique.

An index is the primary index for a table if its Primary property is set to Yes. Each table can have only one primary index.


AddColon, AutoLabel Properties

AddColon [image] You can use this property to specify whether a colon follows the text in labels for new controls.

AutoLabel [image] You can use this property to specify whether labels are attached to new controls.

Setting

The AddColon property uses the following settings.

Setting	Description

Yes	A colon follows the text in labels for new controls.

No	A colon doesn't follow the text in labels for new controls.

The AutoLabel property uses the following settings.

Setting	Description

Yes	A label is attached to new controls.

No	A label isn't attached to new controls.

You can set these properties only using a control's default control style.

Remarks

Changes to the default control style setting affect only controls created on the current form or report. To change the default control style for all new forms or reports that you create without using a Microsoft Access wizard, see Specify a new template for forms and reports.


FontItalic, FontUnderline Properties

You can use the FontItalic and FontUnderline properties to specify these font characteristics in reports and controls.

Setting

The FontItalic property uses the following settings.

Setting	Description	Visual Basic
Yes	Text is italic.	True (-1)
No	(Default) Text is normal.	False (0)
The FontUnderline property uses the following settings.

Setting	Description	Visual Basic
Yes	Text is underlined.	True
No	(Default) Text is normal.	False
For controls, you can set these properties using the control's property sheet, a macro, or Visual Basic.

You can also set these properties using the Formatting toolbar.

You can set the defaults for these properties using the default control style.

Remarks

For reports, you can use these properties only in an event procedure or in a macro specified by the OnPrint event property setting.


FontName, FontSize Properties

You can use the FontName and FontSize properties to specify these font characteristics in reports and controls.

Reports [image] You use these properties to specify the name and point size of the font used for text with the Print method.

Controls [image] You use these properties to specify the name and point size of the font used for text in a control.

Setting

The FontName property specifies one of the font names displayed on the property sheet, which depend on the fonts installed on your system or in your printer.

The FontSize property uses the following settings.

Setting	Description

8	(Default for all reports and controls except buttons) Text is 8-point type.

10	(Default for command buttons) Text is 10-point type.

<Other sizes>	Text is the indicated size.

When modifying controls, set these properties using the property sheet, a macro, or Visual Basic.

You can also set these properties using the Font Name box and the Font Size box on the Formatting toolbar.

For reports, you can set these properties in an event procedure or in a macro specified by the OnPrint event property setting.

You can set the default for these properties using a control's default control style.

In Visual Basic, you set the FontName property using a string expression that is the name of the desired font and you set the FontSize property using a numeric expression equal to the size of the desired font.

Remarks

If you select a font that your system can't display or that isn't installed, Windows substitutes a similar font.


FontWeight Property

You use the FontWeight property to specify the line width that Windows uses to display and print characters in a control.

Setting

The FontWeight property uses the following settings.

Setting	Visual Basic

Thin	100

Extra Light	200

Light	300

Normal	400

Medium	500

Semi-bold	600

Bold	700

Extra Bold	800

Heavy	900

You can set this property using the control's property sheet, a macro, or Visual Basic. You can also use the Bold button on the Formatting toolbar.

You can set the default for this property using a control's default control style.

Remarks

Font availability depends on your system and printer. If you select a font that your system can't display or that isn't installed, Windows substitutes a similar font.

A font's appearance on screen and in print may differ, depending on your computer and printer. For example, a FontWeight property setting of Thin may look identical to Normal on screen but appear lighter when printed.


LabelAlign, TextAlign Properties

LabelAlign [image] You can use this property to specify the text alignment within attached labels on new controls.

TextAlign [image] You can use this property to specify the text alignment in new controls.

Setting

The LabelAlign property uses the following settings.

Setting	Description
General	(Default) Label text aligns to the left.
Left	Data aligns to the left.
Center	Data is centered.
Right	Data aligns to the right.
You can set the LabelAlign property only in the default control style.

The TextAlign property uses the following settings.

Setting	Description	Visual Basic
General	(Default) Text aligns to the left; numbers and dates align to the right.	0
Left	Data aligns to the left.	1
Center	Data is centered.	2
Right	Data aligns to the right.	3
You can set the TextAlign property in the control's property sheet, a macro, or Visual Basic.

You can also set the TextAlign property using the Formatting toolbar.

Remarks

When created, controls have an attached label. Changes to this default control property setting affect only controls created on the current form or report. To change the default control property settings for all new forms or reports, see Specify a new template for forms and reports.


LabelAlign, TextAlign Properties - Applies To
LabelAlign, TextAlign Properties — Applies To

LabelAlign Property

TextAlign Property


PictureAlignment Property

You can use the PictureAlignment property to specify where a background picture will appear in an image control or on a form or report.

Setting

The PictureAlignment property uses the following settings.

Setting	Description	Visual Basic
Top-left	The picture is displayed at the top left corner of the image control, Form window, or page of a report.	0
Top-right	The picture is displayed at the top right corner of the image control, Form window, or page of a report.	1
Center	(Default) The picture is centered in the image control, Form window, or page of a report.	2
Bottom-left	The picture is displayed at the bottom left corner of the image control, Form window, or page of a report.	3
Bottom-right	The picture is displayed at the bottom right corner of the image control, Form window, or page of a report.	4
Form Center	(Forms only) The form's picture is centered horizontally in relation to the width of the form and vertically in relation to the height the entire form.	5
You can set the PictureAlignment property in the form or report's property sheet, a macro, or using Visual Basic.

This property can be set in any view.

Remarks

The Form Center setting aligns a form's picture in the center of the form itself. All other PictureAlignment property settings align a form's picture in relation to the Form window. If you want to make sure that a form's picture is displayed only on the form or tiled only across the form, set the PictureAlignment property to Form Center.

For reports, the picture appears relative to a full page and not in relation to the size of the actual report. If your report is less than a full page and you want a picture to appear at a location not available through the PictureAlignment property settings, use an image control instead.

When you set the PictureTiling property to Yes, tiling of the picture will begin from the PictureAlignment property setting.


PictureData Property

You can use the PictureData property in Visual Basic to copy the picture in one form, report, or control to another object that supports the Picture property.

Setting

The PictureData property setting is the PictureData property of another image control, command button, toggle button, form, or report.

You set this property using Visual Basic.

Remarks

You can use this property to open a form using a different background picture, depending on actions taken by the user. For example, you might open a Customers form using a different background picture depending on whether the form is opened for data entry or for browsing.

You can also use the PictureData property together with the Timer event and the TimerInterval property to perform simple animation on a form.


PictureData Property Example

The following example uses three image controls to animate a butterfly image across a form. The Hidden1 image control contains a picture of a butterfly with its wings up and the Hidden2 image control contains a picture of the same butterfly with its wings down. Both image controls have their Visible property set to False. The TimerInterval property is set to 200. Each time the Timer event occurs, the picture in the image control Visible1 is changed using the PictureData property of the hidden image controls, and the visible image control is moved 200 twips to the right. The visible image control is moved back to the left side of the form when its Left property value is greater than the width of the form stored in the global variable gfrmWidth. The value of gfrmWidth is set to Me.Width in the form's open event.

Private Sub Form_Timer()

Static picNum As Integer

Select Case picNum

Case Is = 1

Me!Visible1.PictureData = Me!Hidden1.PictureData

Case Is = 2

Me!Visible1.PictureData = Me!Hidden2.PictureData

Case Else

End Select

If picNum = 2 Then picNum = 0

picNum = picNum + 1

If (Me!Visible1.Left > gfrmWidth) Then Me!Visible1.Left = 0

Me!Visible1.Left = Me!Visible1.Left + 200

End Sub


PicturePages Property

You can use the PicturePages property to specify on which page or pages of a report a picture will be displayed.

Setting

The PicturePages property uses the following settings.

Setting	Description	Visual Basic
All Pages	(Default) The picture appears on all pages of the report.	0
First Page	The picture appears only on the first page of the report.	1
No Pages	The picture does not appear on the report.	2
You can set the PicturePages property in a report's property sheet, a macro, or using Visual Basic.


PictureSizeMode Property

You can use the PictureSizeMode property to specify how a picture for a form or report is sized.

Setting

The PictureSizeMode property uses the following settings.

Setting	Description	Visual Basic
Clip	(Default) The picture is displayed in its actual size. If the picture is larger than the form or report then the picture is clipped.	0
Stretch	The picture is stretched horizontally and vertically to fill the entire form, even if its original ratio of height to width is distorted.	1
Zoom	The picture is enlarged to the maximum extent possible while keeping its original ratio of height to width.	3
You can set the PictureSizeMode property in the form or report's property sheet, a macro, or using Visual Basic.

Remarks

When a small picture is used for the Picture property of a form or report, setting the PictureSizeMode to Stretch or Zoom can cause substantial distortion of its resolution. Smaller pictures can be tiled across the entire form or report using the PictureTiling property.


PictureTiling Property

You can use the PictureTiling property to specify whether a background picture is tiled across the entire image control, form window, form, or page of a report.

Setting

The PictureTiling property uses the following settings.

Setting	Description	Visual Basic
Yes	The picture is tiled.	True (-1)
No	(Default) The picture isn't tiled.	False (0)
You can set the PictureTiling property in the object's property sheet, a macro, or using Visual Basic.

Remarks

You can create interesting effects by placing a picture on a form or report and setting the PictureTiling property to Yes. The alignment of the tiled images is affected by the PictureAlignment property setting. For example, if the PictureAlignment property is set to Top-left, tiling begins at the top left of the image control, Form, or Report window.

Note   If the PictureAlignment property is set to Form Center and the PictureTiling property is set to Yes, the background picture of a form will be tiled across the form, not across the Form window.


DDE Function

You can use the DDE function to initiate a dynamic data exchange (DDE) conversation with another application, request an item of information from that application, and display that information in a control on a form or report.

Use the DDE function in the ControlSource property setting of a text box, option group, check box, or combo box on a form.

For example, you can use the DDE function in the ControlSource property of a text box to display data from a specified cell in a Microsoft Excel spreadsheet.

Syntax

DDE(application, topic, item)

The DDE function syntax has the following arguments.

Argument	Description

application	A string expression identifying an application that can participate in a DDE conversation. Usually, application is the name of an .exe file (without the .exe extension) for a Microsoft Windows-based application. For example, to initiate a DDE conversation with Microsoft Excel, type "Excel" for the application argument.

topic	A string expression that is the name of a topic recognized by application. Topic is often a document or data file. Check the other application's documentation for a list of possible topics.

item	A string expression that is the name of a data item recognized by application. Check the other application's documentation for a list of possible items.

Remarks

The DDE function attempts to initiate a DDE conversation with the specified application and topic, and requests the data in item. If successful, the DDE function returns a string that contains the requested information.

If you are requesting data from Microsoft Excel, item might be a row-and-column identifier, such as "R1C1" or the name of a range of cells. In the following example, the DDE function requests information from the cell at row 1, column 1 in a Microsoft Excel worksheet. You can enter this expression for a text box control in the ControlSource property box on the control's property sheet.

= DDE("Excel", "Sheet1", "R1C1")

You can use the DDE function only in the ControlSource property of a text box, option group, check box or combo box. You cannot call the DDE function from Visual Basic.

When you use the DDE function, the control becomes read-only in Form view and Print Preview. For example, if you use the DDE function in a text box, the text in the text box cannot be edited. You must edit the text in the other application. Because the ControlSource property is read-only in Form view and Print Preview, changes to the control must be made in Design view.

The maximum number of DDE conversations that can be open simultaneously is determined by Microsoft Windows and your computer's memory and resources. If the conversation can't be initiated because application isn't running or doesn't recognize topic, or if the maximum number of conversations has already been reached, DDE returns a Null.

Note   The other application may be configured to ignore your request for a DDE conversation. If so, DDE returns a Null. Similarly, you can set Microsoft Access to ignore requests from other applications: click Options on the Tools menu, and on the Advanced tab of the Options dialog box, under DDE Operations, select Ignore DDE Requests.

Note   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.

The following table illustrates how the DDE function behaves when you use it with each of the controls.

Control	Remarks

Text box	The item argument can refer to text or numbers. If item refers to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, DDE returns the first entry. You could use the DDE function with a text box to display the data contained in a cell on the worksheet.

Combo box	The DDE function fills the combo box with the information referred to by item. You can't enter data in the text portion of the box. You might use the DDE function with a combo box to display a list of states or countries that you maintain in a Microsoft Excel worksheet.

Option group	The OptionValue property of each option button in an option group is set to a number. Usually, the first button value is 1, the second is 2, and so on. The number returned by the DDE function determines which option button will be selected.

For example, if DDE returns 2, the second button will be selected. If DDE returns a value that doesn't match any of the OptionValue property settings, none of the buttons will be selected. If item refers to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, DDE returns the first entry.

Check box	If the DDE function returns 0, the check box will be cleared. If DDE returns a nonzero number, such as 1 or -1, the box will be selected. If item refers to text or to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, the check box will be unavailable.


DDESend Function

You can use the DDESend function to initiate a dynamic data exchange (DDE) conversation with another application and send an item of information to that application from a control on a form or report.

Use the DDESend function in the ControlSource property setting of a text box, option group, check box, or combo box on a form.

For example, you can use the DDESend function in the ControlSource property of a text box to send the data displayed in that text box to a specified cell in a Microsoft Excel spreadsheet.

Syntax

DDESend(application, topic, item, data)

The DDESend function has the following arguments.

Argument	Description

application	String expression identifying an application that can participate in a DDE conversation. Usually, application is the name of an .exe file (without the .exe extension) for a Microsoft Windows-based application, such as Microsoft Excel. For example, to initiate a DDE conversation with Microsoft Excel, type "Excel" for the application argument.

topic	String expression that is the name of a topic recognized by application. Topic is often a document or data file. Check the other application's documentation for a list of possible topics.

item	String expression that is the name of a data item recognized by application. Check the other application's documentation for a list of possible items.

data	String or expression containing the data to send to application.

Remarks

The DDESend function initiates a DDE conversation with application and topic, and identifies item as the data item which will receive data. For example, if application is Microsoft Excel, topic might be "Sheet1", and item might be a row-and-column identifier, such as "R1C1", or the name of a range of cells.

The data argument specifies the information you want to send. It can be a literal string, such as "Report prepared by John". Or it can be an expression that includes the result of a function that creates a string, such as "Prepared on " & Date(). If item refers to more than one piece of information, such as a named range in a Microsoft Excel worksheet that contains multiple cells, DDESend sends data to the first entry.

In the following example, the DDESend function sends the string "Some text" to the cell at Row 1, Column 1 in a Microsoft Excel worksheet. You can enter this expression for a text box control in the ControlSource property box on the control's property sheet.

= DDESend("Excel", "Sheet1", "R1C1", "Some text")

Suppose you want to send data from a bound control on a Microsoft Access form to a cell on a Microsoft Excel spreadsheet. The ControlSource property of the bound control already contains a field name or expression. You can create another text box or combo box, and set its ControlSource property an expression including DDESend, where data is the name of the bound control. For instance, if you have a bound text box called Last Name, you can create another text box and set its ControlSource property to the following.

= DDESend("Excel", "Sheet1", "R1C1", [LastName])

This intermediary control must be either a text box or a combo box. You can't use the name of a bound control as the data argument for a check box or option group.

You can use the DDESend function only in the ControlSource property setting of a text box, option group, check box, or combo box on a form. You cannot call the DDESend function from Visual Basic.

When you use DDESend, the control becomes read-only in Form view and Print Preview. Because the ControlSource property is also read-only in Form view and Print Preview, changes to the control must be made in Design view.

The maximum number of DDE conversations that can be open simultaneously is determined by Microsoft Windows and your computer's memory and resources. If the conversation can't be initiated because application isn't running or doesn't recognize topic or if the maximum number of conversations has already been reached, DDESend returns a Null.

Note   The other application may be configured to ignore your DDE conversation. If so, DDESend returns a Null. Similarly, you can set Microsoft Access to ignore requests from other applications: click Options on the Tools menu, and on the Advanced tab of the Options dialog box, under DDE Operations, select Ignore DDE Requests.

Tip   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.

The following table illustrates how DDESend behaves when you use it with each of the controls.

Control	Remarks

Text box	Because the text box appears blank in Form view and Print Preview, you may want to set its Visible property to False.

The data argument can refer to another control. The following example shows how you can send the contents of a control called LastName to a Microsoft Excel worksheet.

= DDESend("Excel", "Sheet1", "R1C1", [LastName])

Combo box	Because the combo box appears blank in Form view and Print Preview, you may want to set its Visible property to False.

The data argument can refer to another control. The following example shows how you can send the contents of a control called LastName to a Microsoft Excel worksheet.

= DDESend("Excel", "Sheet1", "R1C1", [LastName])

Option group	None of the option buttons in the option group is selected in Form view and Print Preview. You may want to make the option group (and its buttons) invisible by setting its Visible property to False.

The data argument must contain numeric data, such as "2". If the data argument isn't numeric, DDESend doesn't send the information and item isn't changed.

Check box	The check box is dimmed in Form view and Print Preview. You may want to make it invisible by setting its Visible property to False.

The data argument must contain numeric data, such as "2". If the data argument isn't numeric, DDESend doesn't send the information and item isn't changed.


Domain Aggregate Functions

Aggregate functions provide statistical information about sets of records (domain). For example, you can use an aggregate function to count the number of records in a particular set of records, or to determine the average of values in a particular field.

The two types of aggregate functions, domain aggregate functions and SQL aggregate functions, provide similar functionality but are used in different situations. The SQL aggregate functions can be included in the syntax of an SQL statement, but can't be called from Visual Basic. Conversely, the domain aggregate functions can be called from Visual Basic. They can also be included in an SQL statement, but using an SQL aggregate function is generally more efficient.

If you are performing statistical calculations from within a macro or module, you must use the domain aggregate functions. You can also use the domain aggregate functions to specify criteria, update values, or create calculated fields in a query expression. You can use either the SQL aggregate or domain aggregate functions in a calculated control on a form or report.

The domain aggregate functions include:

DAvg Function

DCount Function

DLookup Function

DMin, DMax Functions

DStDev, DStDevP Functions

DSum Function

DVar, DVarP Functions


DAvg Function

You can use the DAvg function to calculate the average of a set of values in a specified set of records (domain). Use DAvg in a macro or module, in a query expression, or in a calculated control.

For example, you could use DAvg in the criteria row of a select query on freight cost to restrict the results to only those records for which the freight cost is above the average. Or you could use an expression including DAvg in a calculated control, and display the average value of previous orders next to the value of a new order.

Syntax

DAvg(expr, domain[, criteria])

The DAvg function uses the following arguments.

Part	Description

expr	Expression that identifies the field containing the numeric data you want to average. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr  the name of a table field, a control on a form, a constant, or a function. If expr  includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

domain	String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria	Optional string expression used to restrict the range of data on which DAvg is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DAvg evaluates expr  against the entire domain. Any field included in criteria must also be a field in domain; otherwise DAvg returns a Null.

Remarks

DAvg finds the average value of the field or expression defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

Records containing Null values are not included in the calculation of the average.

Whether you use DAvg in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DAvg to specify criteria in the Criteria row of a query. For example, suppose you want to view a list of all products ordered in quantities above the average order quantity. You could create a query on the Orders and Products tables, and include the Product Name field and the Quantity field, with the following expression in the Criteria row beneath the Quantity field.

> DAvg("[Quantity]", "Orders")

You can also use DAvg within a calculated field expression in a query, or in the Update To row of an update query.

Note   You can use either DAvg or Avg in a calculated field expression in a totals query. If you use DAvg, values are averaged before the data is grouped. If you use Avg, the data is grouped before values in the field expression are averaged.

Use DAvg in a calculated control when you need to specify criteria to restrict the range of data on which DAvg is performed. For example, to display the average cost of freight for shipments sent to California, set the ControlSource property of a text box to the following expression.

= DAvg("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to average all records in domain, use the Avg function.

You can use DAvg in a module or macro or in a calculated control on a form if a field that you need to display is not in the record source on which your form is based. For example, suppose you have a form based on the Orders table, and you want to include the Quantity field from the Order Details table in order to display the average number of items ordered by a particular customer. You can use DAvg to perform this calculation and display the data on your form.

Tips   If you use DAvg in a calculated control, you may want to place the control on the form header or footer so that the value for this control is not recalculated each time you move to a new record.

If the data type of the field from which expr is derived is a number, DAvg returns a Double. If you use DAvg in a calculated control, include a data type conversion function in the expression to improve performance.

Although you can use DAvg to determine the average of values in a field in a foreign table, it may be more efficient to create a query that contains all of the fields that you need, and then base your form or report on that query.

Note   Unsaved changes to records in domain are not included when you use this function. If you want the DAvg function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.


DAvg Function Example

This example returns the average freight cost for orders shipped to the United Kingdom before January 1, 1995. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK and ShippedDate is greater than 1-1-95. Note that the keyword AND is included in the string to separate the multiple fields in the criteria argument. All records included in the DAvg calculation will have both of these criteria.

Dim dblX As Double

dblX = DAvg("[Freight]", "Orders", _

"[ShipCountry] = 'UK' AND [ShippedDate] > #1-1-95#")

The next example calculates an average using a variable, strCountry, in the criteria argument. Note that single quotation marks (') are included in the string expressions, so that when all of the strings are concatenated, the string literal UK will be enclosed in single quotation marks. In this example, the keyword OR is used to separate the multiple fields. This example will return all records that have either or both criteria.

Dim dblX As Double, strCountry As String

strCountry = "UK"
dblX = DAvg("[Freight]", "Orders", _

"[ShipCountry] = '" & strCountry & "'OR [ShippedDate] > #1-1-95#")


DCount Function

You can use the DCount function to determine the number of records that are in a specified set of records (domain). Use DCount in a macro or module, in a query expression, or in a calculated control.

For example, you could use DCount in a module to return the number of records in an Orders table that correspond to orders placed on a particular date.

Syntax

DCount(expr, domain[, criteria])

The DCount function uses the following arguments.

Part	Description

expr	Expression that identifies the field for which you want to count records. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr  the name of a table field, a control on a form, a constant, or a function. If expr  includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

domain	String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria	Optional string expression used to restrict the range of data on which DCount is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DCount evaluates expr  against the entire domain. Any field included in criteria must also be a field in domain; otherwise DCount returns a Null.

Remarks

DCount finds the number of records in the field or expression defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

Use DCount to count the number of records in a domain when you don't need to know their particular values. Although the expr argument can perform a calculation on a field, DCount simply tallies the number of records. The value of any calculation performed by expr is unavailable.

Whether you use DCount in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

Use DCount in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display the number of orders to be shipped to California, set the ControlSource property of a text box to the following expression:

= DCount("[OrderID]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to count all records in domain without specifying any restrictions, use the Count function.

Tip   The Count function has been optimized to speed counting of records in queries. Use Count in a query expression instead of DCount, and set optional criteria to enforce any restrictions on the results. Use DCount when you must count records in a domain from within a code module or macro, or in a calculated control.

You can use DCount to count the number of records containing a particular field that is not in the record source on which your form or report is based. For example, you could display the number of orders in the Orders table in a calculated control on a form based on the Products table.

The DCount function doesn't count records that contain Null values in the field referenced by expr, unless expr  is the asterisk (*) wildcard character. If you use an asterisk, DCount calculates the total number of records, including those that contain Null fields. The following example calculates the number of records in an Orders table.

intX = DCount("*", "Orders")

If domain is a table with a primary key, you can also count the total number of records by setting expr to the primary key field, since there will never be a Null in the primary key field.

If expr identifies multiple fields, separate the field names with a concatenation operator, either an ampersand (&) or the addition operator (+). If you use an ampersand to separate the fields, DCount returns records containing a Null value as well as records containing data. If you use the addition operator, DCount returns only records containing data. The following example demonstrates the effects of each operator when used with a field that contains no Null values (ShipName) and a field that contains Null values (ShipRegion).

intW = DCount("[ShipName]", "Orders")	' Returns 1078.
intX = DCount("[ShipRegion]", "Orders")	' Returns 834.
intY = DCount("[ShipName] + [ShipRegion]", "Orders")	' Returns 834.
intZ = DCount("[ShipName] & [ShipRegion]", "Orders")	' Returns 1078.

Note   The ampersand (&) is the preferred operator for performing string concatenation. You should avoid using the addition operator (+) for anything other than numeric addition, unless you specifically wish to propagate nulls through an expression.

Unsaved changes to records in domain are not included when you use this function. If you want the DCount function to be based on the changed values, you must first save the changes by clicking Save Record on the File menu, moving the focus to another record, or using the Update method.


DCount Function Example

This example returns the number of orders shipped to the United Kingdom after January 1, 1995. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK and ShippedDate is greater than 1-1-95.

intX = DCount("[ShippedDate]", "Orders", _

"[ShipCountry] = 'UK' AND [ShippedDate] > #1-1-95#")

In the next example, the criteria argument includes the current value of a combo box called ShipCountry. The values in the ShipCountry combo box come from the field ShipCountry in an Orders table. Note that the reference to the control is not included in the quotation marks that denote the strings. This ensures that each time the DCount function is called, Microsoft Access will obtain the current value from the control.

intX = DCount("[ShippedDate]", "Orders", "[ShipCountry] = '" _

& Forms!Orders![ShipCountry] & "'AND [ShippedDate] > #1-1-95#")


DFirst, DLast Functions

You can use the DFirst and DLast functions to return a random record from a particular field when you simply need any value from that field.

Syntax

DFirst(expr, domain[, criteria])

DLast(expr, domain[, criteria])

The DFirst and DLast functions use the following arguments.

Argument	Description

expr	Expression that identifies the field from which you want find the first or last value. It can be either a string expression identifying a field in a table or query, or an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

domain	String expression identifying the set of records that constitutes the domain.

criteria	Optional string expression used to restrict the range of data on which DFirst or DLast is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DFirst and DLast evaluate expr against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DFirst and DLast return a Null.

Remarks

You can use DFirst and DLast in a calculated control on a form or report, in a query expression, or in a macro or module.

You can use DFirst and DLast to return a random record in a table or query.

If you want to return the first or last record in a set of records, you should create a query sorted as either Ascending or Descending and set the TopValues property to 1. For more information, see the TopValues property topic. From Visual Basic, you can also create a Recordset object, and use the MoveFirst or MoveLast method to return the first or last record in a set of records.


DLookup Function

You can use the DLookup function to get the value of a particular field from a specified set of records (domain). Use DLookup in a macro or module, in a query expression, or in a calculated control on a form or report.

You can use DLookup to display the value of a field that is not in the record source for your form or report. For example, suppose you have a form based on an Order Details table. The form displays the OrderID, ProductID, UnitPrice, Quantity, and Discount fields. However, the ProductName field is in another table, the Products table. You could use DLookup in a calculated control to display the ProductName on the same form.

Syntax

DLookup(expr, domain[, criteria])

The DLookup function uses the following arguments.

Part	Description

expr	Expression that identifies the field whose value you want to return. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr  the name of a table field, a control on a form, a constant, or a function. If expr  includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

domain	String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria	Optional string expression used to restrict the range of data on which DLookup is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DLookup evaluates expr  against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DLookup returns a Null.

Remarks

DLookup finds a value in the field or expression defined by expr from the table or query referred to by domain, according to any restrictions specified by criteria.

DLookup returns a single field value based on the information specified in criteria. Although criteria is an optional argument, if you don't supply a value for criteria, DLookup returns a random value in the domain.

If no record satisfies criteria or if domain contains no records, DLookup returns a Null.

If more than one field meets criteria, DLookup returns the first occurrence. You should specify criteria that will ensure that the field value returned by DLookup is unique. You may want to use a primary key value for your criteria, such as [EmployeeID] in the following example, to ensure that DLookup returns a unique value.

X = DLookup("[LastName]", "Employees", "[EmployeeID] = 1")

Whether you use DLookup in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DLookup to specify criteria in the Criteria row of a query, within a calculated field expression in a query, or in the Update To row in an update query.

You can also use DLookup in an expression in a calculated control on a form or report if the field that you need to display is not in the record source on which your form or report is based. For example, suppose you have an Orders form with a text box called SKU that displays the ProductID field, and you want to look up ProductName from a Products table, based on the value in the text box. You could create another text box and set its ControlSource property to the following expression.

=DLookup("[ProductName]", "Products", "[ProductID] ='" _

& Forms!Orders!SKU & "'")

Tips   Although you can use DLookup to display a value from a field in a foreign table, it may be more efficient to create a query that contains the fields that you need from both tables, and base your form or report on that query.

You can also use the Lookup Wizard to find values in a foreign table.

Note   Unsaved changes to records in domain are not included when you use this function. If you want the DLookup function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.


DLookup Function Example

This example returns name information from the CompanyName field of the record satisfying criteria. The domain is a Shippers table. The criteria argument restricts the resulting set of records to those for which ShipperID equals 1.

Dim strX As String

strX = DLookup("[CompanyName]", "Shippers", "[ShipperID] = 1")

The following example from the Shippers table uses the form control ShipperID to provide criteria for DLookup. Note that the reference to the control is not included in the quotation marks that denote the strings. This ensures that each time the DLookup function is called, Microsoft Access will obtain the current value from the control.

Dim strX As String

strX = DLookup("[CompanyName]", "Shippers", "[ShipperID] =" _

& Forms!Shippers!ShipperID)

The next example uses a variable, intSearch, to perform a lookup.

Dim intSearch As Integer, strX As String

intSearch = 1
strX = DLookup("[CompanyName]", "Shippers", _

"[ShipperID] = " & intSearch)


DMin, DMax Functions

You can use the DMin and DMax functions to determine the minimum and maximum values in a specified set of records (domain). Use DMin and DMax in a macro or module, in a query expression, or in a calculated control.

For example, you could use DMin and DMax in calculated controls on a report to display the greatest and least order amounts for a particular customer. Or you could use DMin in a query expression to display all orders with a discount greater than the minimum possible discount.

Syntax

DMin(expr, domain[, criteria])

DMax(expr, domain[, criteria])

The DMin and DMax functions use the following arguments.

Argument	Description

expr	Expression that identifies the field for which you want to find the minimum or maximum value. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

domain	String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria	Optional string expression used to restrict the range of data on which DMin or DMax is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DMin and DMax evaluate expr  against the entire domain. Any field included in criteria must also be a field in domain, otherwise DMin and DMax returns a Null.

Remarks

DMin and DMax find the least and greatest value in the field or expression defined by expr from the table or query referred to by domain, according to any restrictions specified by criteria.

DMin and DMax return the minimum and maximum values that satisfy criteria. If expr  identifies numeric data, DMin and DMax return numeric values. If expr identifies string data, they return the string that is first or last alphabetically.

DMin and DMax ignore Null values in the field referenced by expr. However, if no record satisfies criteria or if domain contains no records, DMin and DMax return a Null.

Whether you use DMin or DMax in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DMin and DMax to specify criteria in the Criteria row of a query, in a calculated field expression in a query, or in the Update To row of an update query.

Note   You can use DMin and DMax or Min and Max in a calculated field expression in a totals query. If you use DMin or DMax, values are evaluated before the data is grouped. If you use Min or Max, the data is grouped before values in the field expression are evaluated.

Use DMin or DMax in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display the maximum freight charged for an order shipped to California, set the ControlSource property of a text box to the following expression.

=DMax("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to find the minimum or maximum value of all records in domain, use the Min or Max function.

You can use DMin or DMax in a module or macro or in a calculated control on a form if the field that you need to display is not in the record source on which your form is based.

Tip   Although you can use DMin or DMax to find the minimum or maximum value from a field in a foreign table, it may be more efficient to create a query that contains the fields that you need from both tables, and base your form or report on that query.

Note   Unsaved changes to records in domain are not included when you use these functions. If you want the DMax or DMin function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.


DMin, DMax Functions Example

This example returns the lowest and highest values from the Freight field for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK.

Dim curX As Currency, curY As Currency

curX = DMin("[Freight]", "Orders", "[ShipCountry] = 'UK'")
curY = DMax("[Freight]", "Orders", "[ShipCountry] = 'UK'")

In the next example, the criteria argument includes the current value of a text box called OrderDate. The text box is bound to an OrderDate field in an Orders table. Note that the reference to the control is not included in the double quotation marks (") that denote the strings. This ensures that each time the DMax function is called, Microsoft Access obtains the current value from the control.

Dim curX As Currency

curX = DMax("[Freight]", "Orders", "[OrderDate] = #" _

& Forms!Orders!OrderDate & "#")

In the next example, the criteria expression includes a variable, dteOrderDate. Note that number signs (#) are included in the string expression, so that when the strings are concatenated, they will enclose the date.

Dim dteOrderDate As Date, curX As Currency

dteOrderDate = #3/30/95#
curX = DMin("[Frieght]", "Orders", _

"[OrderDate] = #" & dteOrderDate & "#")


DStDev, DStDevP Functions

You can use the DStDev and DStDevP functions to estimate the standard deviation across a set of values in a specified set of records (domain). Use DStDev and DStDevP in a macro or module, in a query expression, or in a calculated control on a form or report.

Use DStDevP to evaluate a population, and DStDev to evaluate a population sample.

For example, you could use the DStDev function in a module to calculate the standard deviation across a set of students' test scores.

Syntax

DStDev(expr, domain[, criteria])

DStDevP(expr, domain[, criteria])

The DStDev and DStDevP functions use the following arguments.

Argument	Description

expr	Expression that identifies the numeric field on which you want to find the standard deviation. It can be a string expression identifying a field from a table or query, or it can be an expression that performs a calculations on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

domain	String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria	Optional string expression used to restrict the range of data on which DStDev or DStDevP is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DStDev and DStDevP evaluate expr  against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DStDev and DStDevP will return a Null.

Remarks

DStDev and DStDevP find the standard deviation on a set of values defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

If domain refers to fewer than two records or if fewer than two records satisfy criteria, DStDev and DStDevP return a Null, indicating that a standard deviation can't be calculated.

Whether you use DStDev or DStDevP in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DStDev and DStDevP to specify criteria in the criteria row of a select query. For example, you could create a query on an Orders table and a Products table to display all products for which the freight cost fell above the mean plus the standard deviation for freight cost. The criteria row beneath the Freight field would contain the following expression:

> (DStDev("[Freight]", "Orders") + DAvg("[Freight]", "Orders"))

You can use DStDev and DStDevP within a calculated field expression in a query, or in the Update To row of an update query.

Note   You can use DStDev and DStDevP or StDev and StDevP in a calculated field expression in a totals query. If you use DStDev or DStDevP, values are calculated before data is grouped. If you use StDev or StDevP, the data is grouped before values in the field expression are evaluated.

Use DStDev and DStDevP in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display standard deviation for orders to be shipped to California, set the ControlSource property of a text box to the following expression:

=DStDev("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to find the standard deviation across all records in domain, use the StDev or StDevP function.

Tip   If the data type of the field from which expr is derived is a number, DStDev and DStDevP return a Double. If you use DStDev or DStDevP in a calculated control, include a data type conversion function in the expression to improve performance.

Note   Unsaved changes to records in domain are not included when you use these functions. If you want the DStDev or DStDevP function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.


DStDev, DStDevP Functions Example

This example returns estimates of the standard deviation for a population and a population sample for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which the ShipCountry is UK.

Dim dblX As Double, dblY As Double

' Sample estimate.

dblX = DStDev("[Freight]", "Orders", "[ShipCountry] = 'UK'")

' Population estimate.
dblY = DStDevP("[Freight]", "Orders", "[ShipCountry] = 'UK'")

The next example calculates the same estimates using a variable, strCountry, in the criteria argument. Note that single quotation marks (') are included in the string expression, so that when the strings are concatenated, the string literal UK will be enclosed in single quotation marks.

Dim strCountry As String, dblX As Double, dblY As Double

strCountry = "UK"
dblX = DStDev("[Freight]", "Orders", _

"[ShipCountry] = '" & strCountry & "'")
dblY = DStDevP("[Freight]", "Orders", _

"[ShipCountry] = '" & strCountry & "'")


DSum Function

You can use the DSum functions to calculate the sum of a set of values in a specified set of records (domain). Use DSum in a macro or module, in a query expression, or in a calculated control.

For example, you could use DSum in a calculated field expression in a query to calculate the total sales made by a particular employee over a period of time. Or you could use DSum in a calculated control to display a running sum of sales for a particular product.

Syntax

DSum(expr, domain[, criteria])

The DSum function uses the following arguments.

Argument	Description

expr	Expression that identifies the numeric field whose values you want to sum. It can be a string expression identifying a field in a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr the name of a table field, a control on a form, a constant, or a function. If expr includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function.

domain	String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria	Optional string expression used to restrict the range of data on which DSum is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DSum evaluates expr  against the entire domain. Any field included in criteria must also be a field in domain; otherwise, DSum returns a Null.

Remarks

DSum finds the sum of values in the field or expression defined by expr, in the table or query referred to by domain, according to any restrictions specified by criteria.

If no record satisfies the criteria argument or if domain contains no records, DSum returns a Null.

Whether you use DSum in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DSum to specify criteria in the Criteria row of a query, in a calculated field in a query expression, or in the Update To row of an update query.

Note   You can use either DSum or Sum in a calculated field expression in a totals query. If you use DSum, values are calculated before data is grouped. If you use Sum, the data is grouped before values in the field expression are evaluated.

You may want to use DSum when you need to display the sum of a set of values from a field that is not in the record source for your form or report. For example, suppose you have a form which displays information about a particular product. You could use DSum to maintain a running total of sales of that product in a calculated control.

Tip   If you need to maintain a running total in a control on a report, you can use the RunningSum property of that control if the field on which it is based is included in the record source for the report. Use DSum to maintain a running sum on a form.

Note   Unsaved changes to records in domain are not included when you use this function. If you want the DSum function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.


DSum Function Example

This example totals the values from the Freight field for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK.

Dim curX As Currency

curX = DSum("[Freight]", "Orders", "[ShipCountry] = 'UK'")

The next example calculates a total using two separate criteria. Note that single quotation marks (') and number signs (#) are included in the string expression, so that when the strings are concatenated, the string literal will be enclosed in single quotation marks, and the date will be enclosed in number signs.

Dim curX As Currency
curX = DSum("[Freight]", "Orders", _

"[ShipCountry] = 'UK' AND [ShippedDate] > #1-1-95#")

You can use a domain function in the Update To row of an update query. For instance, suppose you want to track current sales by product in a Products table. You could add a new field called SalesSoFar to the Products table, and run an update query to calculate the correct values and update the records. Create a new query based on the Products table, and choose Update from the Query menu. Add the SalesSoFar field to the query grid, and enter the following in the Update To row:

DSum("[Quantity]*[UnitPrice]", "Order Details", _

"[ProductID] = " & [ProductID])

When the query is run, Microsoft Access calculates the total amount of sales for each product, based on information from an Order Details table. The sum of sales for each product is added to the Products table.


DVar, DVarP Functions

You can use the DVar and DVarP functions to estimate variance across a set of values in a specified set of records (domain). Use DVar and DVarP in a macro or module, in a query expression, or in a calculated control on a form or report.

Use DVarP to evaluate variance across a population, and DVar to evaluate variance across a population sample.

For example, you could use the DVar function to calculate the variance across a set of students' test scores.

Syntax

DVar(expr, domain[, criteria])

DVarP(expr, domain[, criteria])

The DVar and DVarP functions use the following arguments.

Arguments	Description

expr	Expression that identifies the numeric field on which you want to find the variance. It can be a string expression identifying a field from a table or query, or it can be an expression that performs a calculation on data in that field. You can include in expr  the name of a table field, a control on a form, a constant, or a function. If expr  includes a function, it can be either built-in or user-defined, but not another domain aggregate or SQL aggregate function. Any field included in expr  must be a numeric field.

domain	String expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria	Optional string expression used to restrict the range of data on which DVar or DVarP is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, DVar and DVarP evaluate expr  against the entire domain. Any field included in criteria must also be a field in domain; otherwise DVar and DVarP return a Null.

Remarks

DVar and DVarP find the variance of a set of values defined by expr in the table or query referred to by domain, according to any restrictions specified by criteria.

If domain refers to fewer than two records or if fewer than two records satisfy criteria, DVar and DVarP return a Null, indicating that a variance can't be calculated.

Whether you use DVar or DVarP in a macro or module, a query expression, or a calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use DVar and DVarP to specify criteria in the Criteria row of a select query; in a calculated field expression in a query; or in the Update To row of an update query.

Note   You can use DVar and DVarP or Var and VarP in a calculated field expression in a totals query. If you use DVar or DVarP, values are calculated before data is grouped. If you use Var or VarP, the data is grouped before values in the field expression are evaluated.

Use DVar and DVarP in a calculated control when you need to specify criteria to restrict the range of data on which the function is performed. For example, to display a variance for orders to be shipped to California, set the ControlSource property of a text box to the following expression.

= DVar("[Freight]", "Orders", "[ShipRegion] = 'CA'")

If you simply want to find the standard deviation across all records in domain, use the Var or VarP function.

Note   Unsaved changes to records in domain are not included when you use these functions. If you want the DVar or DVarP function to be based on the changed values, you must first save the changes by choosing the Save Record command from the File menu, moving the focus to another record, or using the Update method.


DVar, DVarP Functions Example

This example returns estimates of the variance for a population and a population sample for orders shipped to the United Kingdom. The domain is an Orders table. The criteria argument restricts the resulting set of records to those for which ShipCountry equals UK.

Dim dblX As Double, dblY As Double

' Sample estimate.

dblX = DVar("[Freight]", "Orders", "[ShipCountry] = 'UK'")

' Population estimate.
dblY = DVarP("[Freight]", "Orders", "[ShipCountry] = 'UK'")

The next example returns estimates using a variable, strCountry, in the criteria argument. Note that single quotation marks (') are included in the string expression, so that when the strings are concatenated, the string literal UK will be enclosed in single quotation marks.

Dim strCountry As String, dblX As Double

strCountry = "UK"
dblX = DVar("[Freight]", "Orders", "[ShipCountry] = '" _

& strCountry & "'")


Calculating Fields in Domain Aggregate Functions

You can use the string expression argument (the expr argument) in a domain aggregate function to perform a calculation on values in a field. For example, you can calculate a percentage (such as a surcharge or sales tax) by multiplying a field value by a fraction.

The following table provides examples of calculations on fields from an Orders table and an Order Details table.

Calculation	Example
Add a number to a field	"[Freight] + 5"
Subtract a number from a field	"[Freight] - 5"
Multiply a field by a number	"[Freight] * 2"
Divide a field by a number	"[Freight] / 2"
Add one field to another	"[UnitsInStock] + [UnitsOnOrder]"
Subtract one field from another	"[ReorderLevel] - [UnitsInStock]"
You would most likely use a domain aggregate function in a macro or module, in a calculated control on a form or report, or in a criteria expression in a query.

For example, you can calculate the average discount amount for all orders in an Order Details table. Multiply the Unit Price and Discount fields to determine the discount for each order, then calculate the average. Enter the following example in a module.

Dim dblX As Double

dblX = DAvg("[UnitPrice] * [Discount]", "[Order Details]")


Activate, Deactivate Events

These events occur:

Activate [image] When a form or report receives the focus and becomes the active window.

Deactivate [image] When a form or report loses the focus to a Table, Query, Form, Report, Macro, or Module window, or to the Database window.

Note   The Deactivate event doesn't occur when a form or report loses the focus to a dialog box, to a form for which the PopUp property is set to Yes, or to a window in another application.

Remarks

You can make a form or report active by opening it, clicking it or a control on it, or by using the SetFocus method in Visual Basic (for forms only).

The Activate event can occur only when a form or report is visible.

The Activate event occurs before the GotFocus event; the Deactivate event occurs after the LostFocus event.

When you switch between two open forms, the Deactivate event occurs for the form being switched from, and the Activate event occurs for the form being switched to. If the forms contain no visible, enabled controls, the LostFocus event occurs for the first form before the Deactivate event, and the GotFocus event occurs for the second form after the Activate event.

When you first open a form, the following events occur in this order:

Open ⇒ Load ⇒ Resize ⇒ Activate ⇒ Current

When you close a form, the following events occur in this order:

Unload ⇒ Deactivate ⇒ Close

When you close a report, the following events occur in this order:

Unload ⇒ Close ⇒ Deactivate


Activate, Deactivate Events - Macros
Activate, Deactivate Events — Macros

To run a macro when the Activate or Deactivate event occurs, set the OnActivate or OnDeactivate property to the name of the macro.

Remarks

You can use the ShowToolbar action in an Activate or Deactivate macro to display or hide a custom toolbar. Use the Activate or Deactivate event to display or hide custom toolbars when you have more than one form loaded at a time. If you have only one form loaded at a time, you can use the Open and Close events.

If you use a Deactivate macro to hide a custom toolbar, also make sure to hide the toolbar in response to the Unload event for the form or report, because the Deactivate event doesn't occur when a form or report is unloaded. Don't use the GotFocus or LostFocus event to hide a custom toolbar, because these events aren't triggered on forms or reports that contain enabled controls.

You can't use the CancelEvent action in an Activate or Deactivate macro.


Activate, Deactivate Events - Event Procedures
Activate, Deactivate Events — Event Procedures

To create an event procedure that is executed when the Activate or Deactivate event occurs, set the OnActivate or OnDeactivate property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Activate( )

Private Sub Report_Activate( )

Private Sub Form_Deactivate( )

Private Sub Report_Deactivate( )

Remarks

You can use Activate and Deactivate event procedures to display and hide custom toolbars. If you use a Deactivate event procedure to hide a custom toolbar, also make sure to hide the toolbar in response to the Unload event for the form or report, because the Deactivate event doesn't occur when a form or report is unloaded. Don't use the GotFocus or LostFocus event to hide a toolbar, because these events aren't triggered on forms or reports that contain enabled controls.

You can't cancel the Activate or Deactivate event.


Activate, Deactivate Events - Event Procedures Example
Activate, Deactivate Events — Event Procedures Example

The following example shows how to display a custom toolbar named CustomToolbar when a form receives the focus and to hide it when the focus moves to a different window.

Private Sub Form_Activate()

DoCmd.ShowToolbar "CustomToolBar", acToolbarYes	' Display toolbar.

End Sub

Private Sub Form_Deactivate()

DoCmd.ShowToolbar "CustomToolBar", acToolbarNo	' Hide toolbar.

End Sub


Change Event

The Change event occurs when the contents of a text box or the text portion of a combo box changes. Examples of this event include entering a character directly in the text box or combo box or changing the control's Text property setting using a macro or Visual Basic.

Notes

Setting the value of a control using a macro or Visual Basic doesn't trigger this event for the control. You must type the data directly into the control, or set the control's Text property.

This event applies only to controls on a form.

Remarks

By running a macro or executing an event procedure when a Change event occurs, you can coordinate data display among controls. You can also display data or a formula in one control and the results in another control.

The Change event doesn't occur when a value changes in a calculated control or when you select an item from the combo box list.

Note   A Change event can cause a cascading event. This occurs when a macro or event procedure that runs in response to the control's Change event alters the control's contents [image] for example, by changing a property setting that determines the control's value, such as the Text property for a text box. To prevent a cascading event:

If possible, avoid attaching a Change macro or event procedure to a control that alters the control's contents.

Avoid creating two or more controls having Change events that affect each other [image] for example, two text boxes that update each other.

Changing the data in a text box or combo box using the keyboard causes keyboard events to occur in addition to control events like the Change event. For example, if you move to a new record and type an ANSI character in a text box in the record, the following events occur in this order:

KeyDown ⇒ KeyPress ⇒ BeforeInsert ⇒ Change ⇒ KeyUp

The BeforeUpdate and AfterUpdate events for the text box or combo box control occur after you have entered the new or changed data in the control and moved to another control (or clicked Save Record on the Records menu), and thus after all of the Change events for the control.

The NotInList event occurs for combo boxes for which the LimitToList property is set to Yes after you enter a value that is not in the list and attempt to move to another control or save the record. It occurs after all the Change events for the combo box. In this case, the BeforeUpdate and AfterUpdate events for the combo box don't occur, because Microsoft Access doesn't accept a value that is not in the list.


Change Event - Macros
Change Event — Macros

To run a macro when the Change event occurs, set the OnChange property to the name of the macro.

Remarks

You can use a Change macro to synchronize data in two controls; when a change occurs in one control, it can be reflected in the other control.

You can't use the CancelEvent action in a Change macro.


Change Event - Event Procedure
Change Event — Event Procedures

To create an event procedure that is executed when the Change event occurs, set the OnChange property to [Event Procedure], and click the Build button.

Syntax

Private Sub controlname_Change( )

The Change event procedure uses the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the Change event procedure.
Remarks

You can't cancel the Change event.

To prevent a cascading event, avoid creating a Change event procedure for a control that alters the control's contents. If you do create such an event procedure, be sure to set a variable that prevents further changes while the current change is in progress.


Change Event - Event Procedures Example
Change Event — Event Procedures Example

The following example counts the number of characters entered in a text box. If more than three characters are entered, a message is displayed and the count is reset to 0.

To try this example, add the following code to the Declarations section of a module for a form named Orders that contains a text box called ShipRegion.

Private Sub ShipRegion_Change()

' Declare variable as static to preserve value between calls.

Static intLetter As Integer

' Check to see how many letters have been entered.

If intLetter < 3 Then

intLetter = intLetter + 1

' If more than three, reset value of text box.

Else

MsgBox "Only three characters are allowed."

intLetter = 0

Forms!Orders!ShipRegion.Undo

End If

End Sub


Error Event

The Error event occurs when a run-time error is produced in Microsoft Access when a form or report has the focus. This includes Microsoft Jet database engine errors, but not run-time errors in Visual Basic.

Remarks

By executing an event procedure or running a macro when an Error event occurs, you can intercept a Microsoft Access error message and display a custom message that conveys a more specific meaning for your application.


Error Event - Macros
Error Event — Macros

To run a macro when the Error event occurs, set the OnError property to the name of the macro.

Remarks

You can use an Error macro to display a general message whenever a run-time error occurs. However, macros can't return the error code and determine which error occurred, so you typically use event procedures with this event.

You can't use the CancelEvent action in an Error macro.


Error Event - Event Procedures
Error Event — Event Procedures

To create an event procedure that is executed when the Error event occurs, set the OnError property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Error(DataErr As Integer, Response As Integer)

Private Sub Report_Error(DataErr As Integer, Response As Integer)

The Error event procedure uses the following arguments.

Argument	Description
DataErr	The error code returned by the Err object when an error occurs. You can use the DataErr argument with the Error function to map the number to the corresponding error message.
Response	An intrinsic constant determining whether or not an error message is displayed. The Response argument can be one of the following constants. Constant Description acDataErrContinue Ignore the error and continue without displaying the default Microsoft Access error message. You can supply a custom error message in place of the default error message. acDataErrDisplay (Default) Display the default Microsoft Access error message.
Remarks

You can't cancel the Error event.


Error Event - Event Procedures Example
Error Event — Event Procedures Example

The following example shows how you can replace a default error message with a custom error message. When Microsoft Access returns an error message indicating it has found a duplicate key (error code 3022), this event procedure displays a message that gives more application-specific information to users.

Private Sub Form_Error(DataErr As Integer, Response As Integer)

Const conDuplicateKey = 3022

Dim strMsg As String

If DataErr = conDuplicateKey Then

Response = acDataErrContinue

strMsg = "Each employee record must have a unique " _

& "employee ID number. Please recheck your data."

MsgBox strMsg

End If

End Sub


GotFocus, LostFocus Events

These events occur:

GotFocus [image] When a form or control receives the focus.

LostFocus [image] When a form or control loses the focus.

Note   The GotFocus and LostFocus events apply only to forms and controls on a form.

Remarks

These events occur when the focus moves in response to a user action, such as pressing the TAB key or clicking the object, or when you use the SetFocus method in Visual Basic or the SelectObject, GoToRecord, GoToControl, or GoToPage action in a macro.

A control can receive the focus only if its Visible and Enabled properties are set to Yes. A form can receive the focus only if it has no controls or if all visible controls are disabled. If a form contains any visible, enabled controls, the GotFocus event for the form doesn't occur.

You can specify what happens when a form or control receives the focus by running a macro or executing an event procedure when the GotFocus event occurs. For example, by attaching a GotFocus event procedure to each control on a form, you can guide the user through your application by displaying brief instructions or messages in a text box. You can also provide visual cues by enabling, disabling, or displaying controls that depend on the control with the focus.

The GotFocus event differs from the Enter event in that the GotFocus event occurs every time a control receives the focus. For example, suppose the user clicks a check box on a form, then clicks a report, and finally clicks the check box on the form to bring it to the foreground. The GotFocus event occurs both times the check box receives the focus. In contrast, the Enter event occurs only the first time the user clicks the check box. The GotFocus event occurs after the Enter event.

The LostFocus event differs from the Exit event in that the LostFocus event occurs every time a control loses the focus. The Exit event occurs only before a control loses the focus to another control on the same form. The LostFocus event occurs after the Exit event.

If you move the focus on one form to a control that doesn't have the focus on another form, the Exit and LostFocus events for the control that does have the focus on the first form occur before the Enter and GotFocus events for the control on the second form.

If you use the mouse to move the focus from a control on a main form to a control on a subform of that form, the following events occur:

Exit (for the control on the main form)

 ⇓

LostFocus (for the control on the main form)

 ⇓

Enter (for the subform control)

 ⇓

Exit (for the control on the subform that had the focus)

 ⇓

LostFocus (for the control on the subform that had the focus)

 ⇓

Enter (for the control on the subform that the focus moved to)

 ⇓

GotFocus (for the control on the subform that the focus moved to)

If the control you move to on the subform previously had the focus, neither its Enter event nor its GotFocus event occurs, but the Enter event for the subform control does occur. If you move the focus from a control on a subform to a control on the main form, the Exit and LostFocus events for the control on the subform don't occur, just the Exit event for the subform control and the Enter and GotFocus events for the control on the main form.

Note   You often use the mouse or a key such as TAB to move the focus to another control. This causes mouse or keyboard events to occur in addition to the events discussed in this topic.

When you switch between two open forms, the Deactivate event occurs for the first form, and the Activate event occurs for the second form. If the forms contain no visible, enabled controls, the LostFocus event occurs for the first form before the Deactivate event, and the GotFocus event occurs for the second form after the Activate event.

Note   To customize the order in which the focus moves from control to control on a form when you press the TAB key, set the tab order or specify access keys for the controls.


GotFocus, LostFocus Events - Event Procedures
GotFocus, LostFocus Events — Event Procedures

To create an event procedure that is executed when the GotFocus or LostFocus event occurs, set the OnGotFocus or OnLostFocus property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_GotFocus( )

Private Sub controlname_GotFocus( )

Private Sub Form_LostFocus( )

Private Sub controlname_LostFocus( )

The GotFocus and LostFocus event procedures use the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the GotFocus and LostFocus event procedures.
Remarks

You can use a LostFocus event procedure to validate entered data as the user moves the focus from a control. You can also reverse or change conditions that you set up in the object's GotFocus event procedure.

Other uses for LostFocus and GotFocus event procedures are enabling, disabling, hiding, and displaying other objects.

You can't cancel a GotFocus or LostFocus event.


GotFocus, LostFocus Events - Event Procedures Example
GotFocus, LostFocus Events — Event Procedures Example

The following example displays a message in a label when the focus moves to an option button.

To try this example, add the following code to the Declarations section of a module for a form called Contacts that contains an option button named OptionYes and a label named LabelYes.

Private Sub OptionYes_GotFocus()

Me!LabelYes.Caption = "Option button 'Yes' has the focus."

End Sub

Private Sub OptionYes_LostFocus()

Me!LabelYes.Caption = ""	' Clear caption.

End Sub


GotFocus, LostFocus Events - Macros
GotFocus, LostFocus Events — Macros

To run a macro when the GotFocus or LostFocus event occurs, set the OnGotFocus or OnLostFocus property to the name of the macro.

Remarks

You can use a LostFocus macro to validate entered data as the user moves the focus from a control. You can also reverse or change conditions that you set up in the object's GotFocus macro.

Other uses for LostFocus and GotFocus macros are enabling, disabling, displaying, and hiding other objects.

You can't use the CancelEvent action in a GotFocus or LostFocus macro.


KeyDown, KeyUp Events

These events occur:

KeyDown [image] When the user presses a key while a form or control has the focus. This event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

KeyUp [image] When the user releases a key while a form or control has the focus. This event also occurs if you send a keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

Note   The KeyDown and KeyUp events apply only to forms and controls on a form.

Remarks

For both events, the object with the focus receives all keystrokes. A form can have the focus only if it has no controls or all its visible controls are disabled.

A form will also receive all keyboard events, even those that occur for controls, if you set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keys pressed in the form, regardless of which control has the focus. For example, you may want the key combination CTRL+x to always perform the same action on a form.

If you press and hold down a key, the KeyDown event occurs repeatedly until you release the key, then the KeyUp event occurs.

Although the KeyDown and KeyUp events occur when most keys are pressed, they are typically used to recognize or distinguish between:

Extended character keys, such as function keys.

 	Navigation keys, such as HOME, END, PAGE UP, PAGE DOWN, UP ARROW, DOWN ARROW, RIGHT ARROW, LEFT ARROW, and TAB.

Combinations of keys and standard keyboard modifiers (SHIFT, CTRL, or ALT keys).

The numeric keypad and keyboard number keys.

The KeyDown and KeyUp events don't occur when you press:

The ENTER key if the form has a command button for which the Default property is set to Yes.

The ESC key if the form has a command button for which the Cancel property is set to Yes.

Note   To find out the ANSI character corresponding to the key pressed, use the KeyPress event.

The KeyDown and KeyPress events occur when you press or send an ANSI key. The KeyUp event occurs after any event for a control caused by pressing or sending the key. If a keystroke causes the focus to move from one control to another control, the KeyDown event occurs for the first control, while the KeyPress and KeyUp events occur for the second control.

For more information, see Order of events for keystrokes and mouse clicks.


KeyDown, KeyUp Events - Macros
KeyDown, KeyUp Events — Macros

To run a macro when the KeyDown or KeyUp event occurs, set the OnKeyDown or OnKeyUp property to the name of the macro.

Remarks

You can use a KeyDown or KeyUp macro to respond whenever the user presses or releases a key while a form or control has the focus. However, macros can't return the key code and determine which key was pressed, so you typically use event procedures with this event.

You can't use the CancelEvent action in a KeyDown or KeyUp macro.


KeyDown, KeyUp Events - Event Procedure
KeyDown, KeyUp Events — Event Procedures

To create an event procedure that is executed when the KeyDown or KeyUp event occurs, set the OnKeyDown or OnKeyUp property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

Private Sub controlname_KeyDown(KeyCode As Integer, Shift As Integer)

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)

Private Sub controlname_KeyUp(KeyCode As Integer, Shift As Integer)

Remarks

The KeyDown and KeyUp events use the following arguments.

Argument	Description
controlname	A string that is the name of the control affected by the KeyDown and KeyUp event procedures.
KeyCode	A key code, such as vbKeyF1 (the F1 key) and vbKeyHome (the HOME key). To specify key codes, use the intrinsic constants in the Object Browser. You can prevent an object from receiving a keystroke by setting KeyCode to 0.
Shift	The state of the SHIFT, CTRL, and ALT keys at the time of the event. If you need to test for the Shift argument, you can use one of the following intrinsic constants as bit masks: Constant Description acShiftMask Bit mask for the SHIFT key. acCtrlMask Bit mask for the CTRL key. acAltMask Bit mask for the ALT key.
You test for a condition by first assigning each result to a temporary Integer variable and then comparing the Shift argument to an intrinsic constant. Use the And operator with the Shift argument to test whether the condition is greater than 0, indicating that the SHIFT, CTRL, or ALT key was pressed, as in the following example.

ShiftDown = (Shift And acShiftMask) > 0

In an event procedure, you can test for any combination of conditions, as in the following example.

If ShiftDown And CtrlDown Then

.	' Do this if SHIFT and CTRL keys are pressed.

.

.

EndIf

You can use the KeyDown and KeyUp event procedures to interpret the uppercase and lowercase version of each character by testing for both the KeyCode argument and the Shift argument. The KeyCode argument indicates the physical key pressed (thus, A and a are considered the same key), and the Shift argument indicates the state of SHIFT+key and returns either A or a.

Use the KeyDown and KeyUp event procedures for keyboard handlers if you need to respond to both the pressing and releasing of a key.

You can respond to specific keys pressed in a form, regardless of which control has the focus. For example, you may want the key combination CTRL+x to always perform the same action on a form. To make sure a form receives all keyboard events, even those that occur for controls, before they occur for the controls, set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keystrokes in the form's KeyDown, KeyPress and KeyUp events. You can prevent a control from receiving keystrokes you've responded to, and prevent the keyboard events from occurring for the control, by setting the KeyCode argument to 0 for both the KeyDown and KeyUp events, and setting the KeyAscii argument to 0 for the KeyPress event (if the key is an ANSI key). You must set all three arguments to 0 if you don't want the control to receive the keystrokes.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can't cancel the KeyDown or KeyUp event.


Using Intrinsic Constants as Bit Masks

To test for the Shift argument, use a bit mask. The Shift argument is a bit field, with the least significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2). These bits correspond to the values 1, 2, and 4, respectively. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed. For example, if both CTRL and ALT are pressed, the value of the Shift argument is 6.

The intrinsic constants Microsoft Access provides as bit masks for the Shift argument have the following values.

Constant	Value
acShiftMask	1
acCtrlMask	2
acAltMask	3
The constants enable you to test for any combination of keys without having to figure out the unique bit field value for each combination. A bit is set if the key is pressed.


KeyDown, KeyUp Events - Event Procedures Example
KeyDown, KeyUp Events — Event Procedures Example

The following example determines whether you have pressed the SHIFT, CTRL, or ALT key.

To try this example, add the following code to the Declarations section of a module for a form containing a text box named KeyHandler.

Private Sub KeyHandler_KeyDown(KeyCode As Integer, Shift As Integer)

Dim intShiftDown As Integer, intAltDown As Integer

Dim intCtrlDown As Integer

' Use bit masks to determine which key was pressed.

intShiftDown = (Shift And acShiftMask) > 0

intAltDown = (Shift And acAltMask) > 0

intCtrlDown = (Shift And acCtrlMask) > 0

' Display message telling user which key was pressed.

If intShiftDown Then MsgBox "You pressed the SHIFT key."

If intAltDown Then MsgBox "You pressed the ALT key."

If intCtrlDown Then MsgBox "You pressed the CTRL key."

End Sub


KeyPress Event

The KeyPress event occurs when the user presses and releases a key or key combination that corresponds to an ANSI code while a form or control has the focus. This event also occurs if you send an ANSI keystroke to a form or control using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

Note   The KeyPress event applies only to forms and controls on a form.

Remarks

The object with the focus receives all keystrokes. A form can have the focus only if it has no controls or all its visible controls are disabled. A KeyPress event can involve any printable keyboard character, the CTRL key combined with a character from the standard alphabet or a special character, and the ENTER or BACKSPACE key.

A form will also receive all keyboard events, even those that occur for controls, if you set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keys pressed in the form, regardless of which control has the focus. For example, you may want the key combination CTRL+x to always perform the same action on a form.

If you press and hold down an ANSI key, the KeyDown and KeyPress events alternate repeatedly (KeyDown, KeyPress, KeyDown, KeyPress, and so on) until you release the key, then the KeyUp event occurs.

You can use the KeyDown and KeyUp event procedures to handle any keystroke not recognized by the KeyPress event, such as function keys, navigation keys, and any combinations of these with keyboard modifiers (ALT, SHIFT, or CTRL keys). Unlike the KeyDown and KeyUp events, the KeyPress event doesn't indicate the physical state of the keyboard; instead, it indicates the ANSI character that corresponds to the pressed key or key combinations.

KeyPress interprets the uppercase and lowercase of each character as separate key codes and, therefore, as two separate characters.

The KeyDown and KeyPress events occur when you press or send an ANSI key. The KeyUp event occurs after any event for a control caused by pressing or sending the key. If a keystroke causes the focus to move from one control to another control, the KeyDown event occurs for the first control, while the KeyPress and KeyUp events occur for the second control.

For example, if you go to a new record and type a character in the first control in the record, the following events occur:

Current (for the new record)

 ⇓

Enter (for the first control in the new record)

 ⇓

GotFocus (for the control)

 ⇓

KeyDown (for the control)

 ⇓

KeyPress (for the control)

 ⇓

BeforeInsert (for the new record in the form)

 ⇓

Change (for the control if it's a text box or combo box)

 ⇓

KeyUp (for the control)

For more information, see Order of events for keystrokes and mouse clicks.

Note   The BACKSPACE key is part of the ANSI character set, but the DEL key isn't. If you delete a character in a control using the BACKSPACE key, you cause a KeyPress event; if you use the DEL key, you don't.


Key Press Event - Macros
KeyPress Event — Macros

To run a macro when the KeyPress event occurs, set the OnKeyPress property to the name of the macro.

Remarks

You can use a KeyPress macro to respond whenever the user presses an ANSI key while the focus is on a form or control. However, macros can't return the ANSI key code and determine which key was pressed, so you typically use event procedures with this event.

You can use the CancelEvent action in a KeyPress macro to cancel the key or key combination. For example, you may want to disallow the entry of ANSI keystrokes in a control under certain conditions.


KeyPress Event - Event Procedures
KeyPress Event — Event Procedures

To create an event procedure that is executed when the KeyPress event occurs, set the OnKeyPress property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_KeyPress(KeyAscii As Integer)

Private Sub controlname_KeyPress(KeyAscii As Integer)

The KeyPress event uses the following arguments.

Argument	Description
controlname	A string that is the name of the control affected by the KeyPress event procedure.
KeyAscii	Returns a numeric ANSI key code. The KeyAscii argument is passed by reference; changing it sends a different character to the object. Changing the KeyAscii argument to 0 cancels the keystroke so that the object doesn't recognize that a key was pressed.
Remarks

A KeyPress event procedure is useful for intercepting keystrokes entered in a text box or combo box. It enables you to test keystrokes for validity or to format characters as they're typed. Changing the value of the KeyAscii argument changes the character displayed.

You can convert the KeyAscii argument to a character by using the following expression.

Chr(KeyAscii)

You can then perform string operations and translate the character back to an ANSI number that the control can recognize by using the following syntax.

KeyAscii = Asc(character)

Note   The ANSI number for the keyboard combination CTRL+@ is 0. Because Microsoft Access recognizes a KeyAscii value of 0 as a zero-length string (" "), you should avoid using CTRL+@ in your applications.

You can respond to specific keys pressed while a form is open, regardless of which control has the focus. For example, you may want the key combination CTRL+x to always perform the same action on a form. To make sure a form receives all keyboard events, even those that occur for controls, before they occur for the controls, set the KeyPreview property of the form to Yes. With this property setting, all keyboard events occur first for the form, and then for the control that has the focus. You can respond to specific keystrokes in the form's KeyDown, KeyPress, and KeyUp events. You can prevent a control from receiving keystrokes you've responded to, and prevent the keyboard events from occurring for the control, by setting the KeyCode argument to 0 for both the KeyDown and KeyUp events, and setting the KeyAscii argument to 0 for the KeyPress event. You must set all three arguments to 0 if you don't want the control to receive the keystrokes.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can't cancel the KeyPress event in an event procedure, but you can cancel it in a macro.


KeyPress Event - Event Procedures Example
KeyPress Event — Event Procedures Example

The following example converts text entered in a text box to uppercase as the text is typed in, one character at a time.

To try this example, add the following code to the Declarations section of a module for a form that contains a text box named ShipRegion.

Private Sub ShipRegion_KeyPress(KeyAscii As Integer)

Dim strCharacter As String

' Convert ANSI value to character string.

strCharacter = Chr(KeyAscii)

' Convert character to upper case, then to ANSI value.

KeyAscii = Asc(UCase(strCharacter))

End Sub


Load, Unload Events

These events occur:

Load [image] When a form is opened and its records are displayed. The Load event can occur when an application starts, when the OpenForm action is used, or when the user opens a form by choosing the Open button in the Database window.

Unload [image] When a form is closed but before it's removed from the screen. When the form is reloaded, Microsoft Access redisplays the form and reinitializes the contents of all its controls.

Remarks

The Unload event is caused by user actions such as:

Clicking Close on the File menu or a form's Control menu.

Running the Close action in a macro.

Quitting an application by choosing the End Task button in the Microsoft Windows Task List.

Quitting Windows while an application is running.

By running a macro or executing an event procedure when a form's Unload event occurs, you can verify that the form should be unloaded or specify actions that should take place when the form is unloaded. You can also open another form or display a dialog box requesting the user's name to make a log entry indicating who used the form.

When you first open a form, the following events occur in this order:

Open ⇒ Load ⇒ Resize ⇒ Activate ⇒ Current

If you're trying to decide whether to use the Open or Load event for your macro or event procedure, one significant difference is that the Open event can be canceled, but the Load event can't. For example, if you're dynamically building a record source for a form in an event procedure for the form's Open event, you can cancel opening the form if there are no records to display.

Note   When you create macros or event procedures for events related to the Load event, such as Activate and GotFocus, be sure that they don't conflict (for example, make sure you don't cause something to happen in one macro or procedure that is canceled in another) and that they don't cause cascading events.

The Unload event occurs before the Close event. The Unload event can be canceled, but the Close event can't.


Load, Unload Events - Macros
Load, Unload Events — Macros

To run a macro when the Load or Unload event occurs, set the OnLoad or OnUnload property to the name of the macro.

Remarks

You can use a Load macro to carry out actions for the controls or records on a form after the form opens. For example, you can specify default settings for controls.

You can't use the CancelEvent action in a Load macro.

You can use the CancelEvent action in an Unload macro to cancel unloading of the records. This also cancels closing of the form.

If a form's Unload macro carries out a CancelEvent action, you won't be able to close the form. You must either correct the condition that caused the CancelEvent action to be carried out or open the macro and delete the CancelEvent action. If the form is modal, you won't be able to open the macro or work in any other windows in the application.


Load, Unload Events - Event Procedures
Load, Unload Events — Event Procedures

To create an event procedure that is executed when the Load or Unload event occurs, set the OnLoad or OnUnload property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Load( )

Private Sub Form_Unload(Cancel As Integer)

The Unload event uses the following argument.

Argument	Description
Cancel	The setting determining whether to unload the form. Setting Cancel to True (-1) prevents the form from being unloaded.
Remarks

You can place initialization code in a form's Load event procedure. For example, you can specify default settings for controls and initialize form-level variables.

You can't cancel the Load event.

In an Unload event procedure, you can include any form-level validation code you might need to close the form or save the data it contains to a file.

If Cancel is set to True for a form that is modal, you may not be able to return control to the rest of the application.


Load, Unload Events - Event Procedures Example
Load, Unload Events — Event Procedures Example

The following example displays the current date in the form's caption when the form is loaded.

Private Sub Form_Load()

Me.Caption = Date

End Sub

The next example prompts the user to verify that the form should close.

To try this example, add the following code to the Declarations section of a module for a form. In Form view, close the form to display the dialog box, and then choose Yes or No.

Private Sub Form_Unload(Cancel As Integer)

If MsgBox("Close form?", vbYesNo) = vbYes Then

Exit Sub

Else

Cancel = True

End If

End Sub


MouseDown, MouseUp Events

These events occur:

MouseDown [image] When the user presses a mouse button.

MouseUp [image] When the user releases a mouse button.

Notes

The MouseDown and MouseUp events apply only to forms, form section, and controls on a form.

These events don't apply to a label attached to another control, such as the label for a text box. They apply only to "freestanding" labels. Pressing and releasing a mouse button in an attached label has the same effect as pressing and releasing the button in the associated control. The normal events for the control occur; no separate events occur for the attached label.

Remarks

You can use a MouseDown or MouseUp event to specify what happens when a particular mouse button is pressed or released. Unlike the Click and DblClick events, the MouseDown and MouseUp events enable you to distinguish between the left, right, and middle mouse buttons. You can also write code for mouse-keyboard combinations that use the SHIFT, CTRL, and ALT keys.

To cause a MouseDown or MouseUp event for a form to occur, press the mouse button in a blank area, record selector, or scroll bar on the form. To cause a MouseDown or MouseUp event for a form section to occur, press the mouse button in a blank area of the form section after selecting the section. To select the form section, click the section header.

The following apply to both MouseDown and MouseUp events:

If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event.

If mouse buttons are pressed in succession, the object that receives the mouse event after the first press receives all mouse events until all buttons are released.

To respond to an event caused by moving the mouse, you use a MouseMove event.


MouseDown, MouseUp Events - Macros
MouseDown, MouseUp Events — Macros

To run a macro when the MouseDown or MouseUp event occurs, set the OnMouseDown or OnMouseUp event property to the name of the macro.

Remarks

You can use a MouseDown or MouseUp macro to respond whenever the user presses or releases a mouse button in a form or control. However, macros can't return the button code and determine which mouse button was pressed, so you typically use event procedures with this event.

You can't use the CancelEvent action in a MouseDown or MouseUp macro, with one exception: You can use the CancelEvent action in a MouseDown macro to cancel the event that occurs when you press the right mouse button. For example, you can cancel the display of a shortcut menu and display your own custom shortcut menu.


MouseDown, MouseUp Events - Event Procedures
MouseDown, MouseUp Events — Event Procedures

To create an event procedure that is executed when the MouseDown or MouseUp event occurs, set the OnMouseDown or OnMouseUp property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)

Private Sub controlname_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)

Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)

Private Sub controlname_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)

The MouseDown and MouseUp events use the following arguments.

Argument	Description
controlname	A string that is the name of the control affected by the MouseDown and MouseUp event procedures.
Button	The button that was pressed (MouseDown) or released (MouseUp) to trigger the event. If you need to test for the Button argument, you can use one of the following intrinsic constants as bit masks: Constant Description acLeftButton Bit mask for the left mouse button. acRightButton Bit mask for the right mouse button. acMiddleButton Bit mask for the middle mouse button.
Shift	The state of the SHIFT, CTRL, and ALT keys when the button specified by the Button argument was pressed or released. If you need to test for the Shift argument, you can use one of the following intrinsic constants as bit masks: Constant Description acShiftMask Bit mask for the SHIFT key. acCtrlMask Bit mask for the CTRL key. acAltMask Bit mask for the ALT key.
X, Y	The x and y coordinates for the current location of the mouse pointer. X and Y are always expressed in twips.
Note   If a mouse button is pressed while the pointer is over a form or control, that object receives all mouse events up to and including the last MouseUp event. This means that the X and Y arguments may not always be relative to the object that receives them.

Remarks

You test for a condition by first assigning each result to a temporary Integer variable and then comparing the Shift or Button argument to a intrinsic constant. Use the And operator with the Button argument to test whether the condition is greater than 0, indicating that the left, middle, or right mouse button was pressed, as in the following example.

LeftDown = (Button And acLeftButton) > 0

In an event procedure, you can test for any combination of conditions, as in the following example.

If ShiftDown And CtrlDown Then
.	' Do this if SHIFT and CTRL keys are pressed.

.

.

EndIf

Note   The Button argument for the MouseDown and MouseUp events differs from the Button argument used for the MouseMove event. For the MouseDown and MouseUp events, the Button argument indicates exactly one button per event; that is, if you press two mouse buttons, two MouseDown (and MouseUp) events will occur, each with a different Button argument setting. For the MouseMove event, the Button argument indicates the current state of all buttons.

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users.

You can't cancel the MouseDown or MouseUp events.


Using Intrinsic Constants as Bit Masks

To test for the Button or Shift arguments, use a bit mask. The Button argument is a bit field with bits corresponding to the left mouse button (bit 0), right mouse button (bit 1), and middle mouse button (bit 2). These bits correspond to the values 1, 2, and 4, respectively. Only one of the bits is set, indicating which button triggered the event.

The intrinsic constants that Microsoft Access provides for the Button argument have the following values.

Constant	Value
acLeftButton	1
acRightButton	2
acMiddleButton	4
The Shift argument is a bit field, with the least significant bits corresponding to the SHIFT key (bit 0), the CTRL key (bit 1), and the ALT key (bit 2 ). These bits correspond to the values 1, 2, and 4, respectively. The Shift argument indicates the state of these keys. Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed. For example, if both CTRL and ALT were pressed, the value of the Shift argument would be 6.

The intrinsic constants that Microsoft Access provides for the Shift argument have the following values.

Constant	Value
acShiftMask	1
acCtrlMask	2
acAltMask	3
You can use the constants to test for any combination of buttons and keys without having to figure out the unique bit field value for each combination. A bit is set if the button or key is pressed.


MouseDown, MouseUp Events - Event Procedures Example
MouseDown, MouseUp Events — Event Procedures Example

The following example shows how you can find out which mouse button caused a MouseDown event.

To try this example, add the following code to the Declarations section of a module for a form.

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, _

X As Single, Y As Single)

If Button = acLeftButton Then MsgBox "You pressed the left button."

If Button = acRightButton Then _

MsgBox "You pressed the right button."

If Button = acMiddleButton Then _

MsgBox "You pressed the middle button."

End Sub


MouseMove Event

The MouseMove event occurs when the user moves the mouse.

Notes

The MouseMove event applies only to forms, form sections, and controls on a form.

This event doesn't apply to a label attached to another control, such as the label for a text box. It applies only to "freestanding" labels. Moving the mouse pointer over an attached label has the same effect as moving the pointer over the associated control. The normal events for the control occur; no separate events occur for the attached label.

Remarks

The MouseMove event is generated continually as the mouse pointer moves over objects. Unless another object generates a mouse event, an object recognizes a MouseMove event whenever the mouse pointer is positioned within its borders.

To cause a MouseMove event for a form to occur, move the mouse pointer over a blank area, record selector, or scroll bar on the form. To cause a MouseMove event for a form section to occur, move the mouse pointer over a blank area of the form section after selecting the section. To select the form section, click the section header.

Notes

Moving a form can trigger a MouseMove event even if the mouse is stationary. MouseMove events are generated when the form moves underneath the pointer. If a macro or event procedure moves a form in response to a MouseMove event, the event can cascade (that is, continually generate MouseMove events).

If two controls are very close together, and you move the mouse pointer quickly over the space between them, the MouseMove event may not occur for the space (for example, this might be the MouseMove event for the form section). In such cases, you may need to respond to the MouseMove event in the contiguous control. as well as in the form section.

To run a macro or execute an event procedure in response to pressing and releasing the mouse buttons, you use the MouseDown and MouseUp events.


MouseMove Event - Macros
MouseMove Event — Macros

To run a macro when the MouseMove event occurs, set the OnMouseMove property to the name of the macro.

Remarks

You can use a MouseMove macro to respond whenever the user moves the mouse over a form or control. However, macros can't return the button code and determine the state of the mouse buttons or determine the coordinates of the mouse pointer when the movement occurs, so you typically use event procedures with this event.

You can't use the CancelEvent action in a MouseMove macro.


MouseMove Event - Event Procedures
MouseMove Event — Event Procedures

To create an event procedure that is executed when the MouseMove event occurs, set the OnMouseMove property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)

Private Sub controlname_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)

The MouseMove event uses the following arguments.

Argument	Description
controlname	A string that is the name of the control affected by the MouseMove event procedure.
Button	The state of the mouse buttons when the event occurs. If you need to test for the Button argument, you can use one of the following intrinsic constants as bit masks: Constant Description acLeftButton Bit mask for the left mouse button. acRightButton Bit mask for the right mouse button. acMiddleButton Bit mask for the middle mouse button.
Shift	The state of the SHIFT, CTRL, and ALT keys when the button specified by the Button argument was pressed or released. If you need to test for the Shift argument, you can use one of the following intrinsic constants as bit masks: Constant Description acShiftMask Bit mask for the SHIFT key. acCtrlMask Bit mask for the CTRL key. acAltMask Bit mask for the ALT key.
X, Y	The x and y coordinates of the current location of the mouse pointer. X and Y are always expressed in twips.
You test for a condition by first assigning each result to a temporary Integer variable and then comparing the Shift or Button argument to as intrinsic constant. Use the And operator with the Button argument to test whether the condition is greater than 0, indicating that the left, middle, or right mouse button was pressed, as in the following example.

LeftDown = (Button And acLeftButton) > 0

In a procedure, you can test for any combination of conditions, as in the following example.

If ShiftDown And CtrlDown Then

.	' Do this if SHIFT and CTRL keys are pressed.

.

.

EndIf

Note   The Button argument for the MouseDown and MouseUp events differs from the Button argument for MouseMove. For the MouseMove event, the Button argument indicates the current state of all buttons; a single MouseMove event can indicate that some, all, or no button is pressed. For example, if you press both the left and right buttons while moving the mouse, the Button argument is set to 3 (1 + 2). For the MouseDown and MouseUp events, the Button argument indicates one button per event.

Remarks

You can use the arguments for the KeyDown, KeyPress, and KeyUp events, in conjunction with the arguments for the MouseDown, MouseUp, and MouseMove events, to make your application work smoothly for both keyboard and mouse users. For example, you may need to coordinate the keyboard focus with the mouse focus. Normally, these are the same. For example, if you move the mouse pointer to a text box and click the mouse button, both the keyboard focus and the mouse focus move to the text box. However, moving the mouse pointer over a control does not move the keyboard focus to that control. You need to click a mouse button, use one of the keyboard navigation keys, or set the focus to the control in the MouseMove event procedure.

Since the MouseMove event occurs for each area of the form it moves over, you can end up with a multitude of MouseMove events if you don't control them. You may want to make sure that if a control or section has received a MouseMove event, the event doesn't occur for the control or section again while the mouse pointer is still on this area of the form. To do this, set and check a module variable that indicates whether the MouseMove event has already occurred for this control or form section.

You can't cancel the MouseMove event.


MouseMove Event - Event Procedures Example
MouseMove Event — Event Procedures Example

The following example determines where the mouse is and whether the left mouse button and/or the SHIFT key is pressed. The X and Y coordinates of the mouse pointer position are displayed in a label control as you move the mouse.

To try this example, add the following code to the Declarations section of a module for a form that contains a label named Coordinates.

Private Sub Detail_MouseMove(Button As Integer, Shift As Integer, _

X As Single, Y As Single)
Dim intShiftDown As Integer, intLeftButton As Integer

Coordinates.Caption = X & " , " & Y

' Use bit masks to determine state of SHIFT key and left button.

intShiftDown = Shift And acLeftButton

intLeftButton = Button And acShiftMask

' Check that SHIFT key and left button are both pressed.

If intShiftDown And intLeftButton > 0 Then

MsgBox "Shift key and left mouse button were pressed."

End If

End Sub


Resize Event

The Resize event occurs when a form is opened and whenever the size of a form changes.

Remarks

This event occurs if you change the size of the form in a macro or event procedure; for example, if you use the MoveSize action in a macro to resize the form.

By running a macro or executing an event procedure when a Resize event occurs, you can move or resize a control when the form it's on is resized. You can also use a Resize event to recalculate variables or reset properties that may depend on the size of the form.

When you first open a form, the following events occur in this order:

Open ⇒ Load ⇒ Resize ⇒ Activate ⇒ Current


Resize Event - Macros
Resize Event — Macros

To run a macro when the Resize event occurs, set the OnResize property to the name of the macro.

Remarks

To repaint the screen every time a form is resized, use the RepaintObject action in the macro you specify for the Resize event.

You can't use the CancelEvent action in a Resize macro.


Resize Event - Event Procedures
Resize Event — Event Procedures

To create an event procedure that is executed when the Resize event occurs, set the OnResize property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Resize( )

Remarks

To repaint the screen every time a form is resized, use the Repaint method in a Resize event procedure.

You can't cancel the Resize event.


Resize Event - Event Procedures Example
Resize Event — Event Procedures Example

The following example shows how a Resize event procedure can be used to repaint a form when it is maximized. When the user clicks a command button labeled "Maximize," the form is maximized and the Resize event is triggered.

To try this example, add the code to the Declarations section of a module for a form called Contacts that contains a command button named Maximize.

Private Sub Maximize_Click()

DoCmd.Maximize

End Sub

Private Sub Form_Resize()

Forms!Contacts.Repaint

End Sub


Retreat Event

The Retreat event occurs when Microsoft Access returns to a previous report section during report formatting.

Remarks

Under certain circumstances, Microsoft Access must return to a previous report section to determine where certain controls and sections are on a report and whether they will fit in a given space. Examples include:

Groups (except for page headers and footers) for which the KeepTogether property is set to either Whole Group or With First Detail.

Subreports or subforms for which the CanGrow and/or CanShrink properties are set to Yes.

Sections on the last page of a report.

In these situations, the Format event occurs as Microsoft Access determines how the sections will fit on the printed page (however, a Print event doesn't occur because the sections aren't being printed yet). If the sections can't be printed, Microsoft Access backs up to the necessary location so that the sections can actually be printed on the following page. The Retreat event occurs for each section past which Microsoft Access retreats. The Format event for each section then occurs again as Microsoft Access prepares to reprint the sections.

For example, whenever Microsoft Access reaches the end of the last page while formatting a report, the Retreat event occurs for each previous section until Microsoft Access reaches the first section at the top of the last page. Then the Format event occurs again for each section on the page, followed by the Print events.

You can run an event procedure or macro when the Retreat event occurs to undo any changes that you made when the Format event occurred for the section. This is useful when your Format event procedure or macro carries out actions, such as calculating page totals or controlling the size of a section, that you only want to perform once for each section.

The Retreat event is also useful for maintaining the positioning of report items. For example, the Sales By Year report in the Northwind sample database uses this event to determine if a page header is printed or not (the page header is printed on pages following a page where the group header has been printed, and the page header isn't printed on the page following a page where the group footer has been printed).


Retreat Event - Macros
Retreat Event — Macros

To run a macro when the Retreat event occurs, set the OnRetreat property to the name of the macro.

Remarks

You can't use the CancelEvent action in a Retreat macro.


Retreat Event - Event Procedures
Retreat Event — Event Procedures

To create an event procedure that is executed when the Retreat event occurs, set the OnRetreat property to [Event Procedure], and click the Build button.

Syntax

Private Sub sectionname_Retreat( )

The Retreat event procedure uses the following argument.

Argument	Description
sectionname	A string that is the name of the section affected by the Retreat event procedure.
Remarks

You can't cancel the Retreat event.


Timer Event

The Timer event occurs for a form at regular intervals as specified by the form's TimerInterval property.

Remarks

By running a macro or executing an event procedure when a Timer event occurs, you can control what Microsoft Access does at every timer interval. For example, you might want to requery underlying records or repaint the screen at specified intervals.

The TimerInterval property setting of the form specifies the interval, in milliseconds, between Timer events. The interval can be between 0 and 65,535 milliseconds. Setting the TimerInterval property to 0 prevents the Timer event from occurring.


Timer Event - Event Procedures
Timer Event — Event Procedures

To create an event procedure that is executed when the Timer event occurs, set the OnTimer property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Timer( )

Remarks

You can't cancel the Timer event.


Timer Event - Event Procedures Example
Timer Event — Event Procedures Example

The following example demonstrates a digital clock you can display on a form. A label control displays the current time according to your computer's system clock.

To try this example, add the following code to the Declarations section of a module for a form that contains a label named Clock. Set the form's TimerInterval property to 1000 milliseconds to update the clock every second.

Private Sub Form_Timer()

Clock.Caption = Time	' Update time display.

End Sub


Timer Event - Macros
Timer Event — Macros

To run a macro when the Timer event occurs, set the OnTimer event property to the name of the macro.

Remarks

You can't use the CancelEvent action in a Timer macro. However, setting the TimerInterval property of the form to 0 prevents the Timer event from occurring.


ReplicationConflictFunction Property

The ReplicationConflictFunction property enables you to use custom conflict resolution code for resolving data conflicts that occur between replicas upon synchronization. When you set this property, Microsoft Access calls your conflict resolution function, rather than the intrinsic Conflict Resolver, when the user requests to resolve conflicts.

Settings

Set the ReplicationConflictFunction property to a text string that is the name of the function you wish to call. Unless this property has been set, Microsoft Access will call its intrinsic Conflict Resolver.

To set this property's value for the first time from Visual Basic, you must create the property and append it to the Properties collection of the UserDefined Document object. You should include error-handling code in your procedure to test for the case in which the property doesn't yet exist in the Properties collection. See the CreateProperty method for more information and an example.

To return control to the intrinsic Conflict Resolver again, remove this property from the Properties collection.

You can also add or delete this property on the Custom tab of the Database Properties dialog box, available by clicking Database Properties on the File menu.

Remarks

If the same record in a replicated database has been changed in one or more replicas, conflicts will result when you synchronize a replica with the replica set. When you choose to resolve these conflicts, Microsoft Access calls its built-in Conflict Resolver. The Conflict Resolver adopts the data from the replica in which this record has been changed the greatest number of times, and propagates this data to the other replicas. Any changes to the record that have been made in a different replica are overwritten, and those changes are recorded in the conflict table named tablename_conflict.

If you prefer a different system of conflict resolution, you can write custom procedures to resolve conflicts, and override the built-in functionality by setting the ReplicationConflictFunction property. You should create a single function that acts as a point of entry into your conflict resolution code. Then set the ReplicationConflictFunction property to the name of this function.


AccessError Method

Use the AccessError method to return the descriptive string associated with a Microsoft Access error.

Syntax

[application].AccessError(errornumber)

The AccessError method uses the following arguments.

Argument	Description
application	Optional. The Application object.
errornumber	The number of the error for which you wish to return a descriptive string.
Remarks

You can use the AccessError method to return the descriptive string associated with a Microsoft Access error when the error has not actually occurred. If the Microsoft Access error has occurred, you can use either the AccessError method or the Description property of the Visual Basic Err object to return the string.

You can use the AccessError method to return a descriptive string from within a form's Error event. You can also use the AccessError method to return a descriptive string when you have raised a Microsoft Access error using the Raise method of the Err object.

The AccessError method will return a string associated only with Microsoft Access errors and Visual Basic errors. It will not return descriptive strings associated with data access errors. Use the Description property of the data access Error object to return strings associated with data access errors.


Conversion and Compatibility Issues

Each new version of Microsoft Access includes improvements designed to help you develop more powerful, intuitive, and flexible applications. For the most part, Microsoft Access for Windows 95 (version 7.0) is compatible with its predecessors; however, in a few cases new features can conflict with existing code. For more information, see Appendix A of Building Applications with Microsoft Access for Windows 95.

Converting Access Basic Code to Visual Basic

Converting Code That Calls a DLL

Converting Libraries and Add-ins

Converting Microsoft Access Tables, Forms, and Reports

Converting SendKeys Key Combinations

DAO Object Library Compatibility

Macro Actions and Methods of the DoCmd Object

New Style for Intrinsic Constants

Scoping and Object Naming Compatibility


Converting Libraries and Add-ins

If you use add-ins or library databases created in previous versions of Microsoft Access, you must convert them to version 7.0 format before you can use them with applications in Microsoft Access 95. Just as when you convert your 1.x and 2.0 applications, you may need to make some changes to the objects, macros, and procedures in your library databases and add-ins in order to make sure that they function properly.

For more information on library databases, see Chapter 12, "Using Library Databases and Dynamic-Link Libraries," in Building Applications with Microsoft Access for Windows 95.

Referencing and Loading Library Databases

Before using a library in Microsoft Access 95, you must establish a reference to the library database from each of your applications that uses it.

A library database should contain only Visual Basic code, which you can call from any application that maintains a reference to that library. In previous versions of Microsoft Access, you loaded a library database at startup by creating an entry in the Libraries section of your .ini file. Most of the information that was previously stored in an .ini file is now stored in the Windows Registry. However, there is no need to create a Windows Registry key set in order to use a library database.

An add-in may contain objects in addition to Visual Basic code. You must create a Windows Registry key set in order to use the objects in your add-ins.

Circular References Between Libraries

In Microsoft Access 95, you can't implement circular library references. In other words, once you've created a reference from Library A to Library B, you cannot create a reference from Library B to Library A.

Custom Add-ins Menu Behavior

In previous versions of Microsoft Access, add-ins automatically appeared on the Add-ins submenu on the File menu. In Microsoft Access 95, the Add-ins submenu is on the Tools menu.


Scoping and Object Naming Compatibility

Visual Basic introduces several changes to scoping rules that affect the names you choose for your objects, modules, and procedures.

Modules and Other Objects with the Same Name

When you name a module, avoid prefacing module names with "Form_" or "Report_." Naming a module in this way could conflict with existing form or report class names.

If you have a module in an application created with a previous version of Microsoft Access that doesn't follow these naming rules, Microsoft Access automatically changes the name of the module to conform to these guidelines when you convert your application. For example, a module named Form_Orders in a Microsoft Access version 1.x or 2.0 database would be converted to a module named Form1_Orders.

Modules and Procedures with the Same Name

You can have a procedure with the same name as a module. However, to call that procedure from an expression anywhere in your application, you must use a fully qualified name for the procedure, including both the module name and the procedure name, as in the following example.

IsLoaded.IsLoaded("Orders")

Procedures and Controls with the Same Name

If you call a procedure from a form, and that procedure has the same name as a control on the form, you must fully qualify the procedure call with the name of the module in which it resides. For example, if you want to call a procedure named PrintInvoice that resides in a standard module named Utilities, and there is also a button on the same form named PrintInvoice, use the fully qualified name Utilities.PrintInvoice when you call the procedure from your form or form module.

Controls with Similar Names

You can't have a control with a name that differs from an existing control's name by only a space or a symbol. For example, if you have a control named [Last_Name], you can't have a control named [Last Name] or [Last+Name].

Modules with the Same Names as Type Libraries

You can't save a module with the same name as a type library. If you try to save a module with the name "DAO", "Access", or "VBA", you'll get an error stating that the name conflicts with an existing module, project, or object library. Similarly, if you've set a reference to another type library, such as the Microsoft Excel type library, you can't save a module with the name "Excel".

Fields with the Same Names as Methods

If a field in the table has the same name as a data access method on a Recordset object, you can't refer to the corresponding field in the recordset with the . (dot) syntax. You must use the ! (exclamation point) syntax, or Microsoft Access will generate an error. The following example shows how to refer to a field called AddNew in a recordset opened on a table called Contacts.

Dim dbs As Database, rst As Recordset

Set dbs = CurrentDb

Set rst = dbs.OpenRecordset("Contacts")

Debug.Print rst!AddNew

Modules with the Same Names as Visual Basic Functions

If you save a module with the same name as an intrinsic Visual Basic function, Microsoft Access will generate an error when you try to run that function. For example, if you save a module named MsgBox, then try to run a procedure that calls the MsgBox function, Microsoft Access generates the error "Expected variable or procedure, not module."

Modules with the Same Names as Objects

If a database created with a previous version of Microsoft Access includes a module that has the same name as a Microsoft Access object or a data access object, you may encounter compilation errors when you convert your database to Microsoft Access 95. For example, a module named "Form" or "Database" may generate a compilation error. To avoid these errors, rename the module.

Naming Fields Used in Expressions or Bound to Controls on Forms and Reports

When you create a field in a table that will be bound to a control on a report or used in an expression in the ControlSource property of a control or a report, avoid assigning the field a name that is the same name as a method of the Application object. To see a list of methods of the Application object, click Object Browser on the View menu while in the module editor. Choose the Microsoft Access type library from the Libraries/Databases drop-down list box, choose Application from the Modules/Classes list, and view the methods of the Application object in the Methods/Properties list.

When you create a field in a table that will be bound to a control on a form or report, avoid assigning the field any of the following names: AddRef, GetIDsOfNames, GetTypeInfo, GetTypeInfoCount, Invoke, QueryInterface, Release.


Macro Actions and Methods of the DoCmd Object

Some macro actions work differently in Microsoft Access 95 than in previous versions. These changes can affect macros or code that you developed in version 1.x or 2.0 using the DoCmd statement to carry out Microsoft Access actions. The following actions have changed:

The CopyObject Action

If you specify the current database as the Destination Database argument for the CopyObject action, the copied object doesn't show up in the database immediately. To view or use the copied object, you must close and reopen the database.

The TransferSpreadsheet Action

Microsoft Access 95 can't import Microsoft Excel version 2.0 spreadsheets or Lotus 1-2-3 version 1.0 spreadsheets. If your converted database contains a macro that provided this functionality in Microsoft Access version 1.x or 2.0, converting the database changes the Spreadsheet Type action argument to Microsoft Excel version 3.0 (if you originally specified Microsoft Excel version 2.0), or causes an error if you originally specified Lotus 1-2-3 version 1.0 format.

The TransferText Action

If you use the TransferText action to export a query, and the query contains two or more fields which have the same name, you must rename the fields in the query before you can export the query using this action. You can rename a field in query Design view.

The TransferText and TransferSpreadsheet Actions

In Microsoft Access 95, you can't use an SQL statement to specify data to export using the TransferText action or the TransferSpreadsheet action. Instead of using an SQL statement, you must first create a query and then specify the name of the query in the Table Name action argument.


Converting Access Basic Code to Visual Basic

In Microsoft Access 95, Visual Basic for applications replaces Access Basic, which was used in previous versions of Microsoft Access. In most respects, Visual Basic is identical to Access Basic, and Microsoft Access makes most necessary conversions to your code automatically when you convert your database.

However, the conversion process makes some changes to your code that you need to be aware of, and there are some additional changes that you must make yourself in order for your application to run successfully in Microsoft Access 95.

Calling the Windows Application Programming Interface

If your existing Access Basic code made calls to the Windows Application Programming Interface (API), you may need to modify these calls when you convert your database. Previous versions of Microsoft Access were 16-bit applications and ran on 16-bit versions of Windows. Microsoft Access 95 is a 32-bit application and runs on 32-bit versions of Windows [image] Windows 95 and Windows NT.

Check any Declare statements to ensure that they refer to the correct dynamic-link libraries (DLLs). For example, 32-bit versions of Windows include the User32.dll; in older versions of Windows, this DLL was called User.dll. For more information, see Converting Code That Calls a DLL.

The names of some functions in the Windows API have changed. Additionally, functions in the 32-bit Windows API are case-sensitive. For a complete reference, see the Microsoft Win32 Software Development Kit.

Changes to Modules

In previous versions of Microsoft Access, modules containing general procedures not specific to any form or report module were called global modules. In Microsoft Access 95, these are called standard modules.

In Microsoft Access 95, form and report modules are now class modules, meaning that they can act as templates for a user-defined object. Any public procedures in a form or report class module become methods and properties of the form or report when you create a new instance of the form or report.

The CurrentDb Function Versus DBEngine(0)(0)

Use the CurrentDb function instead of DBEngine(0)(0) to return a Database object variable that points to the current database. The CurrentDb function creates another instance of the current database, while DBEngine(0)(0) refers to the open copy of the current database. Using DBEngine(0)(0) limits your ability to use more than one variable of type Database which refers to the current database.

The DBEngine(0)(0) syntax is still supported, so Microsoft Access doesn't change your code during the conversion process. However, you should consider making this modification to your code in order to avoid possible conflicts in a multiuser environment.

The CurDir Function

The CurDir function behaves differently than it did in version 1.x or 2.0 due to the way that applications interact with Windows 95. Since each application has its own current directory, setting the current directory in Windows 95 by double-clicking on an icon doesn't affect the current directory in Microsoft Access. The CurDir function in Microsoft Access 95 always returns the current path.

Assigning an OLE Object to a Variable

If you manipulate OLE objects or other binary data in your code, you should use an array of bytes to store binary data. In previous versions of Microsoft Access, you assigned OLE objects, or other binary data less than 64K in size, to string variables when you needed to manipulate the objects or data in code. You also assigned the data returned by the GetChunk method to string variables. Visual Basic supplies a Byte data type and new byte functions such as LeftB and RightB. In Microsoft Access 95, you should store binary data in an array of bytes instead of a string variable, and you should use the byte functions to manipulate that data.

Declare DDE Channels as Variant or Long

If you use the DDEInitiate function to open a DDE channel, you can declare the variable that stores the channel number, which is a Long value, as either a Variant or Long value. In previous versions of Microsoft Access, the channel number was an Integer value, so you must modify any declaration statements in your code which create variables of type Integer to store the channel number.

String Conversion Fails if String Contains a Percent Sign (%)

You can't assign a string containing a percent sign to a variable or a field that has a numeric data type, as in the following example.

Dim intX As Double

intX = "10"	' This works.

intX = "10%"	' This returns an error.

Carrying Out Macro Actions Using the DoCmd Object

To carry out macro actions from code in Microsoft Access 95, use the DoCmd object and its methods. This object replaces the DoCmd statement that you used in previous versions of Microsoft Access to carry out a macro action.

When you convert a database, Microsoft Access automatically converts any DoCmd statements and the actions that they carry out in your Access Basic code to methods of the DoCmd object by replacing the space with the . (dot) operator.

The hWnd Property

If you use the hWnd property in your code to pass a window handle of a form or a report to a Windows routine, you should pass the value directly to the routine. You should not assign the value of this property to a variable. See the following example.

If Not IsZoomed(Screen.ActiveForm.hWnd) Then

DoCmd.Maximize

EndIf

In previous versions of Microsoft Access, the hWnd property of a form or report was an Integer value. In Microsoft Access 95, the hWnd property is a Long value, which you must change your code to accept.

DAO Property Objects versus Access Property Objects

You can't use an object variable in your code to refer to a Category property object. The Category property is no longer supported for Form, Report, and Control objects.

The Parent Property

In Microsoft Access 95, if you use the Parent property of a control in code or in an expression on a form or report, it returns the Form or Report object that contains the control. For example, if CategoryID is a text box on the Categories form, the code Forms!Categories!CategoryID.Parent returns a reference to the Categories form. There are two exceptions: for attached labels, the Parent property now returns the control the label is attached to; and for controls in an option group, it now returns the option group control.

Calling Code in Microsoft Access Wizards

If code in your version 1.x or 2.0 applications calls procedures in Microsoft Access wizards, after you convert your application you must establish a reference from your application to the wizard database that contains the procedures that you call. For more information on establishing references, see Setting References.

In Microsoft Access version 2.0, there was no distinction between wizards and libraries, so their global code was always available to the current database. In Microsoft Access 95, wizards and other add-ins are no longer treated as libraries. In addition, because wizards may change a great deal from one version of Microsoft Access to the next, you may need to rewrite some of your code to adapt to the changes after upgrading to a new version of Microsoft Access.

For code that is no longer provided in the Microsoft Access wizards, such as the AutoDialer, functionality has been added to Utility.mda, a special library database that is provided with Microsoft Access. A reference to this library is automatically added when you convert a database to Microsoft Access 95.

Setting a Reference to a Microsoft Access Database

You cannot set a reference to a database created with a previous version of Microsoft Access from Microsoft Access 95. You must convert the database to a Microsoft Access 95 (version 7.0) database in order to set a reference to it.

Handling OLE Automation Errors

In previous versions of Microsoft Access, an OLE Automation server returned a single error. Visual Basic now enables a server to return error information specific to the error that has occurred. If your existing databases include code to handle a single OLE Automation error, you may have to update that code to handle the more specific errors that will now be returned.

Microsoft Access Errors and the Error Function

In Microsoft Access 95, you can no longer use the Error function to return a description of Microsoft Access errors. For example, the following reference causes an error.

Error(2450)

In Microsoft Access 95, the Error function returns strings for Visual Basic errors, or for the last error stored in the Err object, but not for Microsoft Access errors, with one exception. If a Microsoft Access error actually occurs, you can get the error description by passing the value of the Err object to the Error function, as in the following example.

Error(Err)

Exclamation Point versus Dot Operator When Referencing DAO Objects

If you used the . (dot) operator syntax when referring to Recordset objects in applications created in previous versions of Microsoft Access, you must modify those references to use the ! (exclamation point) operator syntax. Or, if you want to continue using the . (dot) operator syntax, you must establish a reference to the Microsoft DAO 2.5/3.0 Compatibility Library in the References dialog box, available by clicking References on the Tools menu.

Converted Custom Controls

If your application contains custom controls that were set up in version 2.0, you may need to insert the ByVal keyword in front of arguments that are passed to event procedures called from custom control events, as in the following example.

Sub ChangeMonth_Click(ByVal intCurrentYear As Integer)

In order to determine whether an argument needs to be passed by value, click Compile All Modules on the Run menu in module Design view. If you receive the following error message, you need to insert the ByVal keyword in front of the argument.

"Event procedure declaration does not match description of event having the same name."

Because type checking of arguments is improved in Microsoft Access 95, new event procedures created for custom controls automatically have the ByVal keyword inserted when it's needed.

Calling Procedures in Form and Report Modules

In previous versions of Microsoft Access, you couldn't call a procedure defined in a form or report from anywhere but within that form or report module. In Microsoft Access 95, you can call a public procedure in a form or report module from any procedure in the current database. You must qualify the procedure with the class name of the form or report module. For instance, you would call a procedure DisplayMessage that is defined in the module of the Orders form in the following manner.

Form_Orders.DisplayMessage

It's better to place procedures that you will call from outside a form or report in a standard module if possible, rather than in a form or report module.

Referring to Forms and Controls in the Debug Window

When you are testing and debugging code, you must fully qualify all references to objects that you use in the Debug window, unless you have suspended execution in a form or report module. This means that in the Immediate pane of the Debug window, you must use the code Forms!Categories!CategoryID to refer to the CategoryID control on the Categories form in Form view, instead of just CategoryID, even when the Categories form is the current form.

Also, you can't use the Me keyword in the Debug window to refer to an object on a form or report when that form or report is in Design view unless you have suspended the execution of code in the form or report.

Converting Forms and Reports with OLE Custom Controls

When you convert a Microsoft Access 2.0 database for use in Microsoft Access 95 (version 7.0), OLE custom controls on forms and reports may not be converted automatically. Microsoft Access 2.0 supported 16-bit custom controls, while version 7.0 supports only 32-bit custom controls.

If you are converting a database with a form or report that has a 16-bit version of a custom control, and the 32-bit version does not yet exist on your system, Microsoft Access will generate an error message. You must obtain a 32-bit version of each custom control that you wish to update and register it in the system registry. You should then save the form or report in the converted database and close and reopen the database.

Opening a Database Created with a Previous Version of Microsoft Access

When you open a large database created with a previous version of Microsoft Access, but do not convert it to Microsoft Access 95, you may need to increase the maximum buffer size beyond the default. To change this setting, open the Windows registry using a registry editing tool. Navigate through the registry to \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\3.0\Engines\Jet 2.x. Create a new key named ISAM, and within this key create a new DWORD value called MaxBufferSize. Set this value to 1024, decimal base. For more information on editing the Windows registry, see the Windows documentation.

Renaming a Database

When you rename a database, compiled code in the database will be decompiled. To recompile code and save all modules in a compiled state, open the database, open a module, click Compile All Modules on the Tools menu. Then click Save All Modules on the File menu.

Time Values in Query Criteria

When you convert a database from a previous version to Microsoft Access 95, queries that contain criteria based on specific time values in date/time fields may return different results than they did in earlier versions. This may also occur if you link tables from a database in a previous version to a Microsoft Access 95 database. Only the time portion of date/time fields are affected.

Visual Basic Functions Unsupported in Expressions

The following six Visual Basic functions can no longer be used in expressions outside of a user-defined Sub or Function procedure:

EOF	FileAttr
FreeFile	Loc
LOF	Seek
If you need to use one of these functions in an expression outside of a procedure, you can call the function from within a user-defined function that you call from the expression.

Line Numbers in Visual Basic Procedures

You can't assign line numbers greater than 65529 to statements in your Visual Basic procedures. If your converted Microsoft Access application contains line numbers greater than 65529, you must modify them to fall within the acceptable range.

The Next and Previous Procedure Buttons

The Next Procedure and Previous Procedure buttons that were on the Module window toolbar in previous versions aren't available in Microsoft Access 95. If you convert a database with a custom toolbar that contains one of these buttons, you won't receive an error, but the buttons will have no effect when clicked.


DAO Object Library Compatibility

Microsoft Access 95 includes new data access (DAO) objects, methods, and properties that replace those in earlier versions. While the code in Microsoft Access 95 is compatible with all previous DAO code, future versions of Microsoft Access may not provide support for some older objects, methods, and properties. The following sections will help you take advantage of the backward-compatibility features in Microsoft Access 95, as well as help you create new applications and modify current applications to be prepared for conversion to future versions of Microsoft Access.

Taking Advantage of Backward-Compatibility Features

If you want to continue to use the older versions of DAO objects, methods, and properties in your application, you must first establish a reference to the Microsoft DAO 2.5/3.0 Compatibility Library. You establish references in the References dialog box, available by clicking References on the Tools menu in the Module window. The Microsoft DAO 2.5/3.0 Compatibility Library provides complete backward compatibility with all preceding versions of Microsoft Access. A reference to this version of the library is added to applications that you convert to Microsoft Access 95.

The Microsoft DAO 3.0 Object Library doesn't include the older objects, methods, and properties, and is selected by default whenever you create a new database. All new applications created in Microsoft Access 95 should reference only the Microsoft DAO 3.0 Object Library in order to make sure the application isn't using old methods. Also, if your application references only the Microsoft DAO 3.0 Object Library, you won't have to distribute the Microsoft DAO 2.5/3.0 Compatibility Library when you distribute your application to other users.

Tip   If you want to verify that your application only uses the objects, methods, and properties in the Microsoft DAO 3.0 Object Library, you can clear the check box for the Microsoft DAO 2.5/3.0 Compatibility Library, make sure that the Microsoft DAO 3.0 Object Library is selected, and then recompile your application by clicking Compile All Modules on the Run menu in module Design view. If your application recompiles without errors, you no longer need to maintain the reference to the Microsoft DAO 2.5/3.0 Compatibility Library, and you can be sure that your application will work with the next version of DAO.

Preparing for Conversion to Future Versions

The following table lists the objects, methods, and properties that are not included in the Microsoft DAO 3.0 Object Library, as well as the features that have been provided to replace them. You can use the new items in the second column to modify code written in earlier versions of Microsoft Access, so that your application will be prepared for conversion to future versions of Microsoft Access, when the items in the first column will no longer be available.

Functionality not present in DAO 3.0	Recommended DAO 3.0 replacements
FreeLocks	Idle method of the DBEngine object (not needed for Microsoft Access 95 databases)
SetDefaultWorkspace	DefaultUser/DefaultPassword properties of the DBEngine object
SetDataAccessOption	IniPath property of the DBEngine object
Database.BeginTrans	Workspace.BeginTrans
Database.CommitTrans	Workspace.CommitTrans
Database.CreateDynaset	Database.OpenRecordset of type dbOpenDynaset
Database.CreateSnapshot	Database.OpenRecordset of type dbOpenSnapshot
Database.DeleteQueryDef	Delete method of the QueryDefs collection
Database.ExecuteSQL	Database.Execute method and Database.RecordsAffected property
Database.ListTables	Database.TableDefs collection
Database.OpenQueryDef	Database.QueryDefs collection
Database.OpenTable	Database.OpenRecordset of type dbOpenTable
Database.Rollback	Workspace.Rollback
ListFields method of the Table, Dynaset, and Snapshot objects	Recordset.Fields collection
Table.ListIndexes	TableDef.Indexes collection
QueryDef.CreateDynaset	QueryDef.OpenRecordset
QueryDef.CreateSnapshot	QueryDef.OpenRecordset
QueryDef.ListParameters	QueryDef.Parameters collection
Dynaset object	Dynaset-type Recordset object
Snapshot object	Snapshot-type Recordset object
Table object	Table-type Recordset object
CreateDynaset method of the Dynaset and QueryDef objects	Recordset.OpenRecordset with dbOpenDynaset parameter
CreateSnapshot method of the Dynaset and QueryDef objects	Recordset.OpenRecordset with dbOpenSnapshot parameter


New Style for Intrinsic Constants

In Microsoft Access 95, all intrinsic constants are contained in type libraries and are visible in the Object Browser. Microsoft Access includes type libraries for Microsoft Access, Data Access Objects (DAO), and Visual Basic. Each of these type libraries includes intrinsic constants.

Additionally, intrinsic constants in Microsoft Access 95 are a mix of lower and upper case, and parts of the constant are concatenated rather than separated by underscore characters. For example, the constant A_NORMAL in earlier versions is now acNormal.

Intrinsic constants in databases created with previous versions of Microsoft Access will not automatically be converted to the new constant format, but old constants will continue to work without errors. However, it's recommended that you use the new format when writing new code.


Converting SendKeys Key Combinations

If you use the SendKeys statement or action to fill in dialog boxes or choose commands from menus, changes in some dialog boxes and menus may require you to recode the statement or action. For example, the Add-ins submenu has been moved from the File menu to the Tools menu, and the previous Import, Export, and Attach submenus on the File menu have changed to the Get External Data and Save As/Export submenus. Because changes like this are likely to occur for each new version of Microsoft Access, it's a good idea to avoid using the SendKeys statement or action to carry out commands and fill in dialog boxes whenever possible.

Here are some tips you can use to avoid using the SendKeys statement or action:

Before you use the SendKeys statement or action to carry out a menu command, check for an equivalent macro action or Visual Basic method. Most commands that are commonly carried out in a macro or procedure have an equivalent action or method. For example, you can now use the Dropdown method of a combo box rather than the code SendKeys "{F4}".

If a menu command doesn't have an equivalent action or method, use the DoMenuItem action rather than the SendKeys statement or action to carry it out.

Avoid using the SendKeys statement or action to set options in the Options dialog box. New versions of Microsoft Access are likely to have new and changed options, so the code in your SendKeys statement or action could easily break. Instead, use the GetOption and SetOption methods.

When you use the SendKeys statement to carry out an action, consider declaring constants for the values in your SendKeys statement. Defining your keystrokes as constants makes updating your code easier in the future.


Converting Microsoft Access Tables, Forms, and Reports

Several changes introduced by Microsoft Access 95 might affect data entry in your application, and the way that expressions are evaluated on your forms and reports. The following sections provide more information about those changes.

Indexes and Relationships

A Microsoft Access table can contain up to 32 indexes. Very complex tables that are a part of many relationships may exceed the index limit, and you won't be able to convert the database that contains these tables. Version 3.0 of the Microsoft Jet database engine creates indexes on both sides of relationships between tables. If your database won't convert, delete some relationships and try again to convert the database.

The LimitToList Property of Combo Boxes

In Microsoft Access 95, combo boxes accept Null values when the LimitToList property is set to True (-1), whether or not the list contains Null values. In version 2.0, a combo box that had the LimitToList property set to True wouldn't accept a Null value unless the list contained a Null value. If you want to prevent users from entering a Null value using a combo box, set the Required property of the field in the table to Yes.

Menus and In-Place Activation of OLE Objects

In order to make additional functionality available to you while activating OLE objects in place, some menu commands may have been moved to a menu that is not replaced when you activate an OLE server.

Macros in your converted application that use a DoMenuItem action to carry out a version 2.0 menu command when an OLE server is activated won't be affected by the changes. Version 2.0 commands are mapped to their Microsoft Access 95 equivalents.

Referencing a Control on a Read-Only Form

In Microsoft Access 95, you can't use an expression to refer to the value of a control on a read-only form that is bound to an empty record source. In previous versions, the expression would return a Null value. Before you reference a control on a read-only form, you should make sure that the form's record source contains records.

Date Fields and Data Entry

If you enter 3/3 in a field of type Date on a form or a table datasheet, Microsoft Access 95 automatically fills in the current year. However, if you enter 3/3/ in the same field, Microsoft Access returns an error message. You must omit the last date delimiter so that Microsoft Access can translate the date into the proper format.

Buttons Created with the Button Wizard

If you used the Button Wizard in previous versions of Microsoft Access to generate code that called another application, you should delete the button and re-create it using the Button Wizard in Microsoft Access 95.


Database Replication

What Is Database Replication?

You can use database replication to maintain synchronized copies of a database, or replicas, either on the same computer or on different computers with different users over a network.

When you replicate a database, you create a replica set consisting of the original database and at least one replica that is identical to the original. By default, the original database is denoted as the Design Master for the set. However, you can designate another replica in the set as the new Design Master.

The Design Master maintains the database structure for all members of the replica set. You can add, delete, or make changes to database objects at the Design Master and propagate those changes to the other members of the replica set. Only changes made to objects at the Design Master will be propagated to the other members of the replica set when the replicas are synchronized. If you add, delete, or change an object in one of the replicas in the set, that change will not be reflected in the other replicas. You can therefore control changes to the structure of the replicated database.

When data is added, changed, or deleted at the Design Master or in any replica in the set, the change is propagated to all other members of the set upon synchronization. Data changes are not restricted except by the locking rules normally in effect for multiuser databases.

Neither changes to the structure of the database nor changes to the data are propagated to another replica in the set until that replica is synchronized with the replica set. The user of the replica can choose to synchronize with the other members of the set, or you can include an automatic procedure to synchronize the replica based on certain conditions.

In summary, replication provides you with centralized control of the structure of the replicated database, while allowing free exchange of data between members of the replica set. By replicating a database and maintaining individual replicas on users' computers, you can create a multiuser environment with less associated network traffic than if your database resided on a network server.

Creating and Maintaining a Replicated Database

There are several ways to create and maintain a replicated database. The Replication commands, available by clicking on the Tools menu, are simple to use. If you desire programmatic control, you can write code to create and maintain a replicated database using data access objects (DAO). The Replication Manager, available in the Access Developer's Toolkit, is a useful tool for administering a replica set over a network.

These methods are useful for creating and maintaining a replicated database for a workgroup. Replication is also useful when you need to maintain more than one copy of your database for yourself. You can use Briefcase Replication to maintain two synchronized copies of a database if, for example, you've taken one home on a laptop computer.

Replication Commands

The first time you use the Create Replica command from your database (available by clicking Replication on the Tools menu), Microsoft Access converts the database to a replicable database, establishes it as the Design Master, and creates one new replica. Thereafter when you use this command from the Design Master or from a replica in the set, Microsoft Access simply creates another replica. You can use the Create Replica command to create as many additional replicas as you need.

Once you or other users have made changes to two or more members in the replica set, you can use the Synchronize Now command (available by clicking Replication on the Tools menu) to synchronize the changes. If users of two different members have changed the same record in different ways, a conflict table will be generated when you synchronize the members. Use the Resolve Conflicts command to review and resolve any conflicts.

When you save a new database object at the Design Master, you can select the Make Replicable check box to propagate this new object to the replicas in the set. If you leave this box blank, the object will remain local to the Design Master [image] it won't be propagated to the replica set when the set is synchronized.

Replication with Data Access Objects (DAO)

You can create and maintain a replicated database using DAO methods and properties. Use DAO if you require programmatic control over the exchange of data and design information among members of the replica set. For example, you can use DAO to write a procedure that automatically synchronizes a user's replica with the rest of the set when the user opens the database.

You can use the following methods and properties to create and maintain a replicated database.

MakeReplica Method

Synchronize Method

ConflictTable Property

DesignMasterID Property

KeepLocal Property

Replicable Property

ReplicaID Property

ReplicationConflictFunction Property

For more information on database replication, see Chapter 19, "Using Database Replication," in Building Applications with Microsoft Access for Windows 95.


Label Control

You can use labels on a form or report to display descriptive text such as titles, captions, or brief instructions. Labels don't display values from fields or expressions; they're always unbound and they don't change as you move from record to record.

A label can be attached to another control. When you create a text box, for example, it has an attached label that displays a caption for that text box. This label appears as a column heading in the Datasheet view of a form.

When you create a label using the Label tool, the label stands on its own — it isn't attached to any other control. You use stand-alone labels for information such as the title of a form or report, or for other descriptive text. Stand-alone labels don't appear in Datasheet view.


Text Box Control

You can use text boxes on a form or report to display data from a table, query, or SQL statement. This type of text box is called a bound text box because it's bound to data in a field. Text boxes can also be unbound. For example, you can create an unbound text box to display the results of a calculation, or to accept input from a user. Data in an unbound text box isn't saved with the database.


Check Box Control

You can use a check box on a form or report as a stand-alone control to display a Yes/No value from an underlying table, query, or SQL statement. For example, the check box in the following illustration is bound to the Discontinued field in the Products table. The data type of the Discontinued field is Yes/No. If the box contains a check mark, the value is Yes; if it doesn't, the value is No.

When you select or clear a check box that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

You can also use check boxes in an option group to display values to choose from.

It's also possible to use an unbound check box in a custom dialog box to accept user input.


Toggle Button Control

You can use a toggle button on a form as a stand-alone control to display a Yes/No value from an underlying table, query, or SQL statement. For example, the toggle button in the following illustration is bound to the Discontinued field in the Products table. The data type of the Discontinued field is Yes/No. When the button is pressed in, the value in the Products table is Yes. When the button isn't pressed in, the value in the Products table is No.

When you click a toggle button that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

Toggle buttons are most useful when used in an option group with other buttons. In an option group, you can easily tell whether a button is pressed in.

You can use pictures on toggle buttons instead of text. For example, instead of displaying the word "Discontinued" on the toggle button in the first example, you could display a picture of a trash can.

You can also use a toggle button in a custom dialog box to accept user input.


Option Button Control

You can use an option button on a form or report as a stand-alone control to display a Yes/No value from an underlying table, query, or SQL statement. For example, the option button in the following illustration is bound to the Discontinued field in the Products table. The data type of the Discontinued field is Yes/No. If the option button is selected, the value is Yes; if not, the value is No.

When you select or clear an option button that's bound to a Yes/No field, Microsoft Access displays the value in the underlying table according to the field's Format property (Yes/No, True/False, or On/Off).

You can also use option buttons in an option group to display values to choose from.

It's also possible to use an unbound option button in a custom dialog box to accept user input.


Option Group Control

You can use an option group on a form or report to display a limited set of alternatives. An option group makes selecting a value easy since you can just click the value you want. Only one option in an option group can be selected at a time.

An option group consists of a group frame and a set of check boxes, toggle buttons, or option buttons.

If an option group is bound to a field, only the group frame itself is bound to the field, not the check boxes, toggle buttons, or option buttons inside the frame. Instead of setting the ControlSource property for each control in the option group, you set the OptionValue property of each check box, toggle button, or option button to a number that's meaningful for the field the group frame is bound to. When you select an option in an option group, Microsoft Access sets the value of the field to which the option group is bound to the value of the selected option's OptionValue property.

Note   The OptionValue property is set to a number because the value of an option group can only be a number, not text. Microsoft Access stores this number in the underlying table. In the preceding example, if you want to display the name of the shipper instead of a number in the Orders table, you can create a separate table called Shippers that stores shipper names, and then make the ShipVia field in the Orders table a Lookup field that looks up data in the Shippers table.

An option group can also be set to an expression, or it can be unbound. You can use an unbound option group in a custom dialog box to accept user input and then carry out an action based on that input.


Command Button Control

You can use a command button on a form to start an action or a set of actions. For example, you could create a command button that opens another form. To make a command button do something, you write a macro or event procedure and attach it to the button's OnClick property.

Tip   You can create over 30 different types of command buttons with the Command Button Wizard. When you use the Command Button Wizard, Microsoft Access creates the button and the event procedure for you.

You can display text on a command button by setting its Caption property, or you can display a picture by setting its Picture property.


List Box Control

In many cases, it's quicker and easier to select a value from a list than to remember a value to type. A list of choices also helps ensure that the value that's entered in a field is correct.

The list in a list box consists of rows of data. Rows can have one or more columns, which can appear with or without headings.

If a multiple-column list box is bound, Microsoft Access stores the values from one of the columns.

You can use an unbound list box to store a value that you can use with another control. For example, you could use an unbound list box to limit the values in another list box or in a custom dialog box. You could also use an unbound list box to find a record based on the value you select in the list box.

If you don't have room on your form to display a list box, or if you want to be able to type new values as well as select values from a list, use a combo box instead of a list box.


Line Control

You can use the line control to display a horizontal, vertical, or diagonal line on a form or report.

You can use the Border Width button to change the line width. Use the Border Color button to change the color of the border or make it transparent. You can change the line style (dots, dashes, and so on) of the border by using the BorderStyle property.


Rectangle Control

You can use the rectangle control to display a rectangle on a form or report.

You can move a rectangle and the controls in it as a single unit by dragging the mouse pointer diagonally across the entire rectangle to select all of the controls. The entire selection can then be moved to a new position.


Bound Object Frame Control

You can use the bound object frame control to display a picture, chart, or any OLE object stored in a table in a Microsoft Access database. For example, if you store pictures of your employees in a table in Microsoft Access, you can use a bound object frame to display these pictures on a form or report.

This control allows you to create or edit the object from within the form or report using the object application.

A bound object frame is bound to a field in an underlying table.

The field in the underlying table to which the bound object frame is bound must be of the OLE Object data type.

The object in a bound object frame is different for each record. The bound object frame can display linked or embedded objects.

If you want to display objects not stored in an underlying table, use an unbound object frame control or an image control.


Chart Control

The chart control allows you to embed a chart that displays Microsoft Access data from a form or report. You can then edit the chart using Microsoft Graph from within the form or report.

When you place a chart control on a form or report, Microsoft Access displays the Chart Wizard to help you create the chart.

Note   To embed or link a chart using data from other applications, use an unbound object frame or bound object frame control.

Since this control is not displayed on the default toolbar, you can add the Chart control button to the toolbar so the button is available whenever the toolbar is displayed.


Combo Box Control

The combo box control combines the features of a text box and a list box. Use a combo box when you want the option of either typing a value or selecting a value from a predefined list.

In Form view, Microsoft Access doesn't display the list until you click the combo box's arrow.

If you have Control Wizards on before you select the combo box tool, you can create a combo box with a wizard. To turn Control Wizards on or off, click the Control Wizards tool or click Control Wizards on the View menu.

The setting of the LimitToList property determines whether you can enter values that aren't in the list.

The list can be single- or multiple-column, and the columns can appear with or without headings.


Page Break Control

You can use the page break control to mark the start of a new screen or printed page on a form or report.

In a form, a page break is active only when you set the form's DefaultView property to Single Form. Page breaks don't affect a form's datasheet.

In Form view, press the PAGE UP or PAGE DOWN key to move to the previous or next page break.

Position page breaks above or below other controls. Placing a page break on the same line as another control splits that control's data.


Subform/Subreport Control

You can use the subform/subreport control to embed a form in a form or a report in a report.

For example, you can use a form with a subform to present one-to-many relationships, such as one product category with the items that fall into that category. In this case, the main form can display the category ID, name, and description; the subform can display the available products in that category.

Note   Instead of creating the main form, and then adding the subform control to it, you can simultaneously create the main form and subform with a wizard. You can also create a subform or subreport by dragging an existing form or report from the Database window to the main form or report.


Unbound Object Frame Control

You can use the unbound object frame control to displays a picture, chart, or any OLE object not stored in a table. For example, you can use an unbound object frame to display a chart that you created and stored in Microsoft Graph.

This control allows you to create or edit the object from within a Microsoft Access form or report using the application in which the object was originally created.

To display objects that are stored in a Microsoft Access database, use a bound object frame control.

The object in an unbound object frame is the same for every record.

The unbound object frame can display linked or embedded objects.

Note   You can use the unbound object frame or an image control to display unbound pictures in a form or report. The advantage of using the unbound object frame is that you can edit the object directly from the form or report. The advantage of using the image control is that it's faster to display.


Form

A form is a Microsoft Access database object on which you place controls for taking actions or for entering, displaying, and editing data in fields.


Form Section

A form section is part of a form such as a header, footer, or detail section.

You can set section properties which are attributes of a form that affect the appearance or behavior of that section. For example, you can set the CanGrow property to specify whether the section will increase vertically to print all the data the section contains. Section properties are set in form Design view.


Report

A report is a Microsoft Access database object that presents information formatted and organized according to your specifications. Examples of reports are sales summaries, phone lists, and mailing labels.


Report Section

A report section is part of a report such as a header, footer, or detail section.

You can set report section properties which are attributes of a report that affect the appearance or behavior of a specific section. For example, you can set the CanGrow property to specify whether the section will increase vertically to print all the data the section contains. Section properties are set in report Design view.


Index

An index is a Microsoft Access feature that speeds up searching and sorting in a table. You can create an index for a field in the Indexes window of table Design view, or by setting the field's Indexed property to Yes.

Note   The primary key of a table is automatically indexed, and fields for which the data type is Memo or OLE Object can't be indexed.


Image Control

You can use the Image control to add a picture to a form or report. For example, you could include an image control for a logo on an Invoice report.

Control    	Tool

Note   You can use the image control or an unbound object frame for unbound pictures. The advantage of using the image control is that it's faster to display. The advantage of using the unbound object frame is that you can edit the object directly from the form or report.


Bound Control

A bound control is control on a form or report that gets its contents from a field in the underlying table, query, or SQL statement. (The control's ControlSource property is set to a field name in the table, query, or SQL statement.) For example, a text box that displays an employee's last name is bound to the LastName field in the Employees table.


Sorting And Grouping Box

You can use the Sorting And Grouping box to specify the order of your data and define the group levels for a report.

To display the Sorting And Grouping box, click [image] on the toolbar.


Table

A table is the fundamental structure of a relational database management system. In Microsoft Access, a table is an object that stores data in records (rows) and fields (columns). The data is usually about a particular category of things, such as employees or orders.


Color Builder

The Color Builder is a Microsoft Access tool you can use to select colors from the palette or to create custom colors that you can save and use in forms and reports.

To run this builder, click [image] next to the appropriate property in the property sheet.


Query Types

A query is a question about the data in records (rows) and fields (columns) stored in your tables, or a request to perform an action on the data. A query can bring together data from multiple tables to use as the source of data for a form or report. In Microsoft Access, you can create and run the following kinds of queries:

Select queries ask questions about the data stored in your tables and return the result of the query without changing the data. Once the result set is displayed, you can view and, in some cases, change the data in the underlying tables. In contrast, action queries do make changes to your data.

Parameter queries, which are a type of select query, extend the flexibility of other queries by prompting you to enter certain criteria each time the query is run. A parameter query is not, strictly speaking, a separate kind of query; rather, it extends the flexibility of other queries.

Action queries change data or copy data. Action queries include append, delete, make-table, and update queries. In contrast, select queries don't copy or change data; they ask a question and return a set of records.

Append query [image] You can use an append query to add the records in a query's result set to the end of an existing table.

Delete query [image] You can use a delete query to delete a set of rows that match the criteria you specify.

Make-table query [image] You can use a make-table query to create a new table from the result set of an existing query.

Update query [image] You can use an update query to change a set of records according to criteria you specify.

Crosstab queries compute summary totals based on values for each row and column. A query that calculates a sum, average, count, or other type of total on records, and then groups the result by two types of information [image] one down the left side of the datasheet and the other across the top. For example, the Quarterly Orders by Product query in the Northwind sample database is a crosstab query.

SQL-specific queries are queries that can be created only by writing an SQL statement in SQL view. Union, pass-through, and data-definition queries are SQL-specific queries.

Union query [image] An SQL-specific select query that combines corresponding fields from two or more tables or queries into one field. For example, a union query of the Customers table and the Suppliers table results in a snapshot that contains all the specified records from both the Customers table and the Suppliers table.

Pass-through query [image] An SQL-specific query you use to send commands directly to an SQL database server (such as Microsoft SQL Server). With pass-through queries, you work with the tables on the server instead of linking the tables to your Microsoft Access database.

Data-definition query [image] An SQL-specific query that can create or delete an index, or create, alter, or delete a table.


. (dot) Operator

The . (dot) operator shows the relationship among fields, controls, and properties. You can use the operator to refer to a property, method, or collection. The following expression refers to the Visible property of the Customers form.

Forms![Customers].Visible

You can use the . (dot) operator to refer to a field value in an SQL statement, or to another table in a query or filter if it has a field with the same name.


VarType Constants

The VarType function returns a value that provides information about the type of data stored in a variable. The following table shows the equivalent intrinsic constant, the return value, and a description of the variable.

Constant	Value	Description
vbEmpty	0	Uninitialized
vbNull	1	Contains no valid data
vbInteger	2	Integer
vbLong	3	Long integer
vbSingle	4	Single-precision floating-point number
vbDouble	5	Double-precision floating-point number
vbCurrency	6	Currency
vbDate	7	Date
vbString	8	String
vbObject	9	OLE Automation object
vbError	10	Error
vbBoolean	11	Boolean
vbVariant	12	Variant (used only for arrays of Variants)
vbDataObject	13	Non-OLE Automation object
vbByte	17	Byte
vbArray	8192	Array
Note   The intrinsic constant vbArray combined with any other constant indicates an array of that type of variable.


Query Fields

A query filed represents data from a table linked to the query. By default, a query field inherits all the properties that it has in the underlying table or query. For example, if a table design specifies the display format of the Order Date field as Medium Date in the field's Format property, the Order Date field is formatted in the query recordset as Medium Date. Because the underlying field properties are the defaults, they aren't displayed on the property sheet.

If a field property is changed in the table design, the query field automatically inherits the change, If, however, you change a property within the query, the property setting within the table design is overridden. If the property is later changed in the table design, the change isn't reflected in the query.

You can set the properties for query fields within the field properties window of the query Design view.

To open the Field Properties window in query Design view for a query field, click the Properties button on the Query Design toolbar.


Table Fields

Table fields are separate pieces of information that make up a record within a table. You can control the appearance of data, specify default values, and speed up searching and sorting by setting field properties within the Field Properties section of the table Design view.

Microsoft Access uses field properties when you view or edit data. For example, the Format, InputMask, and Caption properties that you set appear in table and query databases. The controls on new forms and reports that are based on the table inherit these properties by default. You can use other properties to set rules for data or to require data entry in your fields, which Microsoft Access enforces whenever you add or edit data in a table.

To open a table in Design view, go to the Database window, click the Tables tab, select the table you want to open, and then click Design.


Comparison of Data Types

The Microsoft Jet database engine recognizes several overlapping sets of data types. In Microsoft Access, there are four different contexts in which you may need to denote a data type [image] in table Design view, in the Query Parameters dialog box, in Visual Basic, and in SQL view in a query.

The following table compares the four sets of data types that correspond to each context. The first column lists the Type property settings available in table Design view and the five FieldSize property settings for the Number data type. The second column lists the corresponding query parameter data types available for designing parameter queries in the Query Parameters dialog box. The third column lists the corresponding Visual Basic data types. The fourth column lists the corresponding Microsoft Access SQL data types defined by the Jet database engine along with their valid synonyms.

Table fields	Query parameters	Visual Basic	Microsoft Jet Database Engine SQL and synonyms
Not supported	Binary	Not supported	BINARY (See Notes) (Synonym: VARBINARY)
Yes/No	Yes/No	Boolean	BOOLEAN (Synonyms: BIT, LOGICAL, LOGICAL1, YESNO)
Number (FieldSize = Byte)	Byte	Byte	BYTE (Synonym: INTEGER1)
AutoNumber (FieldSize = Long Integer)	Not supported	Long	COUNTER (Synonym: AUTOINCREMENT)
Currency	Currency	Currency	CURRENCY (Synonym: MONEY)
Date/Time	Date/Time	Date	DATETIME (Synonyms: DATE, TIME, TIMESTAMP)
Number (FieldSize = Double)	Double	Double	DOUBLE (Synonyms: FLOAT, FLOAT8, IEEEDOUBLE, NUMBER, NUMERIC)
Number or AutoNumber (FieldSize = ReplicationID)	Not supported	Not supported	GUID
Number (FieldSize = Long Integer)	Long Integer	Long	LONG (See Notes) (Synonyms: INT, INTEGER, INTEGER4)
OLE Object	OLE Object	String	LONGBINARY (Synonyms: GENERAL, OLEOBJECT)
Memo	Memo	String	LONGTEXT (Synonyms: LONGCHAR, MEMO, NOTE)
Number (FieldSize = Single)	Single	Single	SINGLE (Synonyms: FLOAT4, IEEESINGLE, REAL)
Number (FieldSize = Integer)	Integer	Integer	SHORT (See Notes) (Synonyms: INTEGER2, SMALLINT)
Text	Text	String	TEXT (Synonyms: ALPHANUMERIC, CHAR, CHARACTER, STRING, VARCHAR)
Not supported	Value	Variant	VALUE (See Notes)
Notes

Microsoft Access itself doesn't use the BINARY data type. It's recognized only for use in queries on attached tables from other database products that support the BINARY data type.

The INTEGER data type in Jet database engine SQL doesn't correspond to the Integer data type for table fields, query parameters, or Visual Basic. Instead, in SQL, the INTEGER data type corresponds to a Long Integer data type for table fields and query parameters and to a Long data type in Visual Basic.

The VALUE reserved word doesn't represent a data type defined by the Jet database engine. However, in Microsoft Access or SQL queries, the VALUE reserved word can be considered a valid synonym for the Visual Basic Variant data type.

If you are setting the data type for a data access object in Visual Basic code, you must set the object's Type property. For a list of data type constants corresponding to the available data types for table fields and parameters, search the online index for "Type property".


Examples of Converting Data Access Code

Microsoft Access includes version 3.0 of the Microsoft Jet database engine, which features a number of new objects, methods, and properties that can improve your existing applications. The following examples demonstrate how to convert code constructs in Microsoft Access databases created with earlier versions of the Jet database engine to take advantage of these new features.

Retrieving a Pointer to the Current Database

Version	Example

1.x	Dim dbs As Database
Set dbs = CurrentDb

2.x	Dim dbs As Database
Set dbs = DBEngine.Workspaces(0).Databases(0)

or	Dim dbs As Database
Set dbs = DBEngine(0)(0)

3.0	Dim dbs As Database
Set dbs = CurrentDb

Note   In Microsoft Access, the current database is the default database in the Databases collection, so you can still use the DBEngine(0)(0) syntax to return a Database object variable pointing to the current database. However, using the CurrentDb function is the preferred means of returning this object variable, because it enables you to create more than one Database object variable that points to the current database.

Opening Another Database

Version	Example

1.x	Set dbs = OpenDatabase("Contacts.mdb")

2.x and later	Set dbs = DBEngine.Workspaces(0).OpenDatabase("Contacts.mdb")

or	Set dbs = Workspaces(0).OpenDatabase("Contacts.mdb")

or	Set dbs = OpenDatabase("Contacts.mdb")

Opening a Table-Type Recordset

Version	Example

1.x	Dim tbl As Table
Set tbl = dbs.OpenTable("Orders")

2.x	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_TABLE)

or	Dim rst As Recordset
Set rst = dbs!Orders.OpenRecordset

3.0	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenTable)

or	Dim rst As Recordset
Set rst = dbs!Orders.OpenRecordset

Opening a Table-Type Recordset Exclusively

Version	Example

1.x	Dim tbl As Table
Set tbl = dbs.OpenTable("Orders", DB_DENY_READ)

2.x	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_TABLE, DB_DENY_READ)

or	Dim rst As Recordset
Set rst = dbs!Orders.OpenRecordset(DB_OPEN_TABLE, DB_DENY_READ)

3.0	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenTable, dbDenyRead)

or	Dim rst As Recordset
Set rst = dbs!Orders.OpenRecordset(dbOpenTable, dbDenyRead)

Opening a Dynaset-Type Recordset

Version	Example

1.x	Dim dyn As Dynaset
Set dyn = dbs.CreateDynaset("Orders")

2.x	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_DYNASET)

or	Set rst = dbs!Orders.OpenRecordset(dbOpenDynaset)

3.0	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenDynaset)

or	Set rst = dbs!Orders.OpenRecordset(dbOpenDynaset)

Opening a Snapshot-Type Recordset

Version	Example

1.x	Dim snp As Snapshot
Set snp = dbs.CreateSnapshot("Orders")

2.x	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", DB_OPEN_SNAPSHOT)

or	Set rst = dbs!Orders.OpenRecordset(DB_OPEN_SNAPSHOT)

3.0	Dim rst As Recordset
Set rst = dbs.OpenRecordset("Orders", dbOpenSnapshot)

or	Set rst = dbs!Orders.OpenRecordset(dbOpenSnapshot)

Listing Fields

Version	Example

1.x	' Given open Table object tbl.
Dim snp As Snapshot
Set snp = tbl.ListFields()
While Not snp.EOF
Debug.Print snp!Name, snp!Type
snp.MoveNext
Wend
snp.Close

2.x	' Given open TableDef object tdf.
Dim intI As Integer, fld As Field
For intI = 0 To tdf.Fields.Count - 1
Set fld = tdf.Fields(intI)
Debug.Print fld.Name, fld.Type
Next intI

3.0	' Given open TableDef object tdf.
Dim fld As Field
For Each fld in tdf.Fields
Debug.Print fld.Name, fld.Type
Next fld

Listing Tables in a Database

Version	Example

1.x	' Given open Database object dbs.
Dim snp As Snapshot
Set snp = dbs.ListTables()
While Not snp.EOF
Debug.Print snp!Name
snp.MoveNext
Wend
snp.Close

2.x	' Given open Database object dbs.
Dim intJ As Integer, tdf As TableDef
For intJ = 0 To dbs.TableDefs.Count - 1
Set tdf = dbs.TableDefs(intJ)
Debug.Print tdf.Name
Next intJ

3.0	' Given open Database object dbs.
Dim tdf As TableDef
For Each tdf in dbs.TableDefs
Debug.Print tdf.Name
Next tdf

Listing a Table's Indexes

Version	Example

1.x	' Given open Table object tbl.
Dim snp As Snapshot
Set snp = tbl.ListIndexes()
While Not snp.EOF
Debug.Print snp!Name
snp.MoveNext
Wend
snp.Close

2.x	' Given open TableDef object tdf.
Dim intI As Integer, idx As Index
For intI = 0 To tdf.Indexes.Count - 1
Set idx = tdf.Indexes(intI)
Debug.Print idx.Name
Next intI

3.0	' Given open TableDef object tdf.
Dim idx As Index
For Each idx in tdf.Indexes
Debug.Print idx.Name
Next idx

Listing a Query's Parameters

Version	Example

1.x	' Given open QueryDef object qdf.
Dim snp As Snapshot
Set snp = qdf.ListParameters()
While Not snp.EOF
Debug.Print snp!Name
snp.MoveNext
Wend
snp.Close

2.x	' Given open QueryDef object qdf.
Dim intI As Integer, prm As Parameter
For intI = 0 to qdf.Parameters.Count - 1
Set prm = qdf.Parameters(i)
Debug.Print prm.Name
Next intI

3.0	' Given open QueryDef object qdf.
Dim prm As Parameter
For Each prm in qdf.Parameters
Debug.Print prm.Name
Next prm

Setting Query Parameters Dynamically

Version	Example

1.x	' Given open Database dbs.
Dim qdf As QueryDef, dyn As Dynaset
Set qdf = dbs.OpenQueryDef("OrdersQuery")
qdf.ParameterName = "[Start date]"
Set dyn = qdf.CreateDynaset()

2.x	' Given open QueryDef object qdf.
Dim intI As Integer, prm As Parameter, rst As Recordset
For intI = 0 To qdf.Parameters.Count - 1
Set prm = qdf.Parameters(intI)
prm.Value = InputBox("Value for " & prm.Name)
Next intI
Set rst = qdf.OpenRecordset

3.0	' Given open QueryDef object qdf.
Dim prm As Parameter, rst As Recordset
For Each prm in qdf.Parameters
prm.Value = InputBox("Value for " & prm.Name)
Next prm
Set rst = qdf.OpenRecordset

Running a Pass-Through Query

Version	Example

1.x	' Given open Database object dbs.
Dim lngRows As Long
' Run stored procedure on server.
lngRows = dbs.ExecuteSQL("EXECUTE SP_StoredProc")

or	Dim snp As Snapshot
Set snp = dbs.CreateSnapshot("EXECUTE SP_StoredProc", DB_SQLPassThrough)

2.x and later	' Given open Database object dbs.
Dim qdf As QueryDef, rst As Recordset
Set qdf = dbs.CreateQueryDef("ODBCQuery")
qdf.Connect = "ODBC;" _
& "DSN=MyServer;" _
& "UID=sa;" _
& "PWD=hithere;" _
& "DATABASE=pubs"
qdf.SQL = "EXECUTE SP_StoredProc"
qdf.ReturnsRecords = True
.
.
.

Set rst = qdf.OpenRecordset

Creating a Temporary Query

Version	Example

1.x	' Given open Database object dbs.
Dim qdf As QueryDef, strTemp As String
strTemp = "TMP:" & User() & Time()
qdf = dbs.CreateQueryDef(strTemp)
qdf.SQL = "UPDATE Table1 SET Table1.Field1 = Field1 * 1.1;"
.
.
.

qdf.Execute
qdf.Close
.
.
.

dbs.DeleteQueryDef(strTemp)

2.x and later	' Given open Database object dbs.
Dim qdf As QueryDef
Set qdf = dbs.CreateQueryDef("", _
"UPDATE Table1 SET Table1.Field1 = Field1 * 1.1;")
.
.
.

qdf.Execute
qdf.Close


What's New for Developers: Overview

Microsoft Access offers a number of new and improved features to help you create great database applications for Windows 95. Microsoft Access includes Visual Basic, a full-featured programming language that not only enables you to create powerful custom database applications, but also makes it easy to integrate your database with other applications through OLE Automation. Microsoft Access also includes version 3.0 of the Microsoft Jet database engine, enhanced for better performance and multiuser scalability.

New Language Functionality

New and Enhanced Language Elements

Microsoft Jet Database Engine

The Integrated Development Environment

Programming with Forms and Reports

OLE Automation

Changes in Scope and Visibility

Improvements in Compilation Performance

Conversion and Compatibility Issues


What's New for Developers: New Language Functionality

Visual Basic provides a number of new language features that were not available in Access Basic in earlier versions of Microsoft Access.

Conditional Compilation

Custom Methods and Properties

Named Arguments and Optional Arguments

Parameter Arrays


What's New for Developers: New and Enhanced Language Elements

Microsoft Access provides an array of new and enhanced objects, methods, properties, functions, statements, data types, and events to enable you to create powerful database applications with Visual Basic.

New and Enhanced Microsoft Access Objects

New Visual Basic Objects

New and Enhanced Data Access Objects

New and Enhanced Methods

New and Enhanced Properties

New and Enhanced Functions

New and Enhanced Statements

New Data Types

New Form and Report Events


New and Enhanced Microsoft Access Objects

Application Object

In Microsoft Access, the Application object is at the top of the object hierarchy, and all other objects and collections are members of it. To control Microsoft Access with OLE Automation, you can create an instance of the Application object, and access all other objects and their properties and methods through it.

From an application acting as an OLE Automation controller, such as Microsoft Excel, you can create a new instance of Microsoft Access in the following way.

Dim appAccess As Access.Application

Set appAccess = CreateObject("Access.Application.7")

From some applications, including Microsoft Visual Basic 4.0, you can use the New keyword to declare an object variable and point it to a new instance of Microsoft Access in one step.

Dim appAccess As New Access.Application

If you use the New keyword to create an instance of Microsoft Access, that instance will not become visible until you have called a method or set or returned a property on the Application object. For example, the following line of code would make the new instance of Microsoft Access visible, and also make it the active application.

appAccess.AppActivate

When the Application object variable goes out of scope, the instance of Microsoft Access that it points to closes. You therefore may want to declare the Application object variable as a module-level variable, which will retain its value until you set it equal to Nothing or until you use the Reset command, available on the Run menu.

Using the DBEngine property of the Application object, you can return a reference to the DBEngine object. Using this reference you can access all data access objects and collections.

DoCmd Object

The DoCmd object replaces the DoCmd statement from earlier versions of Microsoft Access. The actions that were used as arguments to the DoCmd statement are now methods of the DoCmd object. For example, in Microsoft Access 2.0, you might have used the following code to open a form from Access Basic.

DoCmd OpenForm "Orders"

In Microsoft Access 95, you would use the following syntax.

DoCmd.OpenForm "Orders"

When you convert an existing Microsoft Access 2.0 database to Microsoft Access 95 format, code including the DoCmd statement and an action will be automatically converted to the new format.

The DoCmd object is a member of the Application object. You can use the DoCmd object to execute actions from within Microsoft Access, or from another application that is controlling Microsoft Access with OLE Automation.

Controls Collection

In Microsoft Access, each Form object and Report object contains a Controls collection, which includes all controls on the form or report.

ItemsSelected Collection

List boxes and combo boxes in Microsoft Access have an ItemsSelected collection, which contains an index representing each selected row in the list box or combo box. By enumerating through this collection, you can easily return data from all selected rows.

New Document Objects

Microsoft Access provides two new data access objects, the SummaryInfo Document and the UserDefined Document. These Document objects are defined by Microsoft Access, but are available through the data access object hierarchy.

The SummaryInfo Document object contains Summary properties in its Properties collection. You can set these properties on the Summary tab of the Database Properties dialog box, available by clicking Database Properties on the File menu. The UserDefined Document object contains user-defined properties in its Properties collection. You can create and set these properties on the Custom tab of the Database Properties dialog box.

Because these properties are defined by Microsoft Access, the Microsoft Jet database engine doesn't automatically recognize them. To set one of these properties from Visual Basic, you must ensure that it exists in the Properties collection of the appropriate Document object. If it doesn't, you must create the property using the CreateProperty method and append it to the properties collection, or a run-time error will occur. When setting these properties from Visual Basic, you should include error handling code that performs this task when the property does not already exist in the Properties collection.


New Visual Basic Objects

Visual Basic provides three new objects to Microsoft Access: the Collection object, the Err object, and the Debug object.

The Collection object enables you to create your own user-defined collections. The collection defined by a Collection object can contain any combination of Microsoft Access objects, data access objects, OLE Automation objects, or user-defined objects. A collection defined by a Collection object can contain another user-defined collection.

The Err object stores run-time error information and enables you to raise an error programmatically. You can use the Err object to create user-defined errors as well as to obtain information about built-in errors.

The Debug object replaces the Microsoft Access Debug object from previous versions. Its functionality is identical.

The methods and properties available to these objects are listed in the Visual Basic library in the Object Browser.


New and Enhanced Methods

Microsoft Access and Visual Basic provide the following new methods.

Add	OpenQuery
ApplyFilter	OpenReport
Beep	OpenTable
BuildCriteria	OutputTo
CancelEvent	Print
CloseCurrentDatabase	Quit
CopyObject	RefreshTitleBar
DefaultControl	Remove
DefaultWorkspaceClone	Rename
DeleteObject	Repaint
DoMenuItem	Requery
DropDown	Restore
Echo	Run
FindNext	RunMacro
FindRecord	RunSQL
GoToControl	Save
GoToPage	SelectObject
GoToRecord	SendObject
Hourglass	SetMenuItem
InsertText	SetWarnings
Item	ShowAllRecords
Maximize	ShowToolbar
Minimize	SizeToFit
MoveSize	TransferDatabase
NewCurrentDatabase	TransferSpreadsheet
OpenCurrentDatabase	TransferText
OpenForm	Undo
OpenModule


New and Enhanced Functions

Microsoft Access provides the following new and enhanced functions.

Array	InputB
CBool	IsArray
CByte	IsError
CDate	IsMissing
ChrB	IsObject
CVErr	LeftB
FileDateTime	LoadPicture
FileLen	MidB
GetAllSettings	Nz
GetAttr	RightB
GetSetting	TypeName


New and Enhanced Statements

Visual Basic provides the following new statements to Microsoft Access.

DeleteSetting	Property Let
FileCopy	Property Set
For Each...Next	Public
Option Private	SaveSetting
Private	SetAttr
Property Get	With


New Data Types

Visual Basic provides the following new data types to Microsoft Access.

Boolean

Byte

Date


New Form and Report Events

Microsoft Access provides the following new form and report events.

Filter

ApplyFilter

NoData

Page


What's New for Developers: Microsoft Jet Database Engine

Microsoft Access includes version 3.0 of the Microsoft Jet database engine. This is a new 32-bit version of the Jet database engine and has been enhanced for improved performance and multiuser scalability. The Jet database engine also provides database replication functionality and an enhanced data access object (DAO) model.

Performance Improvements in the Microsoft Jet Database Engine

Database Replication

New and Enhanced Data Access Objects

New and Enhanced Data Access Methods and Properties

Using Data Access Objects in Microsoft Visual C++ Applications


What's New for Developers: The Integrated Development Environment

The Microsoft Access development environment provides several new features to make it easier for you to write and debug code. The new development environment includes a new module editor, the Object Browser, the References dialog box, and the Debug window.

Using the Module Editor

Using the Object Browser

Setting References

Using the Debug Window


What's New for Developers: OLE Automation

In Microsoft Access 2.0, you could use OLE Automation to control objects belonging to other applications. With Microsoft Access 95, this functionality is enhanced. Additionally, Microsoft Access acts as an OLE Automation server by providing its own objects for use by other applications.

Using Microsoft Access as an OLE Automation Controller

Using Microsoft Access as an OLE Automation Server


New and Enhanced Properties

Microsoft Access provides the following new properties.

ActiveDatasheet	ImageWidth
AllowAdditions	InSelection
AllowAutoCorrect	InsideHeight
AllowBreakIntoCode	InsideWidth
AllowBuiltInToolbars	KeyPreview
AllowBypassKey	ListIndex
AllowDeletions	MinMaxButtons
AllowEdits	MultiSelect
AllowFullMenus	NewRecord
AllowShortcutMenus	NewValues
AllowSpecialKeys	Object Properties
AllowToolbarChanges	OrderBy
AppIcon	OrderByOn
Application	Parent
AppTitle	Picture
BorderStyle	PictureAlignment
CloseButton	PictureData
CodeContextObject	PicturePages
ControlTipText	PictureSizeMode
ControlType	PictureTiling
CurrentRecord	PictureType
Cycle	RecordsetType
Database Properties	RepeatSection
DataEntry	Selected
DatasheetCellsEffect	SelHeight
DatasheetGridLinesBehavior	SelLeft
DatasheetGridLinesColor	SelTop
DBEngine	SelWidth
Description	ShortcutMenuBar
Dirty	SpecialEffect
DisplayControl	StartupForm
DividingLines	StartupMenuBar
Filter	StartupShortcutMenuBar
FilterLookup	StartupShowDBWindow
FilterOn	StartupShowStatusBar
Format	TripleState
GrpKeepTogether	UserControl
HasContinued	Visible
HasData	Visible (Application Object)
hWndAccessApp	WhatsThisButton
ImageHeight	WillContinue


Microsoft Access Constants - Overview
Microsoft Access Constants – Overview

General

A constant represents a numeric or string value that doesn't change. You can use constants to improve the readability of your Visual Basic code and to make your code easier to maintain. In addition, the use of intrinsic constants ensures that code will continue to work even if the underlying values that the constants represent are changed in later releases of Microsoft Access.

Microsoft Access supports three types of constants:

Symbolic constants, which you create using the Const statement and use in modules.

Intrinsic constants, which are part of Microsoft Access.

System-defined constants: True, False, and Null.

Symbolic Constants

Often, you'll use the same values repeatedly in your code, or you'll find that the code depends on certain numbers that have no obvious meaning. In these cases, you can make the code much easier to read and maintain by using symbolic or user-defined constants, which enable you to use a meaningful name in place of a number or string.

Once you have created a constant using the Const statement, you can't modify it or assign a new value to it. You also can't create a constant that has the same name as an intrinsic constant.

The following examples show some of the ways you can use the Const statement to declare numeric and string constants:

Const conPI = 3.14159265	' PI equals this number.

Const conPI2 = conPI * 2	' A constant used to create another.

Const conVersion = "Version 7.0"	' Declare a String constant.

Intrinsic Constants

In addition to the constants you declare with the Const statement, Microsoft Access automatically declares a number of intrinsic constants and provides access to the Visual Basic for applications (VBA) constants and the Data Access Object (DAO) constants. You can also use constants in other referenced object libraries. For more information on adding references See Setting References.

Any intrinsic constant can be used in a macro or Visual Basic. These constants are available at all times. The specific built-in constants used with a particular function, method, or property are described in the Help topic for that function, method, or property.

Note	You can use the Object Browser to view lists of intrinsic constants from all available object libraries.

Intrinsic constants have a two letter prefix identifying the object library that defines the constant. Constants from the Microsoft Access library are prefaced with ac; constants from the DAO library are prefaced with db; and constants from the VBA library are prefaced with vb. For example:

acForm

dbAppendOnly

vbCurrency

Note   Because the values represented by the intrinsic constants may change in future versions of Microsoft Access, you should use the constants instead of their actual values. You can, however, display the actual value of a constant by choosing the constant in the Object Browser or by typing ?constantname in the Debug window.

You can use intrinsic constants wherever you can use symbolic, or user-defined constants, including in expressions. The following example shows how you might use the intrinsic constant vbCurrency to determine whether varNum is a Variant of VarType 6 (Currency):

Dim varNum As Variant

If VarType(varNum) = vbCurrency Then

Debug.Print "varNum contains Currency data."

Else

Debug.Print "varNum doesn't contain Currency data."

End If

There are several categories of intrinsic constants. For a list of the intrinsic constants in a particular category, click the category below:

Action constants

Data Access Object constants

Event procedure constants

Key code constants

Miscellaneous constants

Security constants

Visual Basic constants

VarType constants

System-Defined Constants

You can use the system-defined constants True, False, and Null anywhere in Microsoft Access. For example, you can use True in the following macro condition expression. The condition is met if the Visible property setting for the Employees form equals True:

Forms![Employees].Visible = True

You can use the constant Null anywhere in Microsoft Access. For example, you can use Null to set the DefaultValue property for a form control using the following expression:

=Null


Security Constants

You can assign permissions to database objects using Visual Basic or set the Permissions property to one of the following constants:

Permissions Property Constants
acSecMacExecute	dbSecDelete
acSecMacReadDef	dbSecDeleteData
acSecMacWriteDef	dbSecFullAccess
acSecFrmRptExecute	dbSecInsertData
acSecFrmRptReadDef	dbSecNoAccess
acSecFrmRptWriteDef	dbSecReadSec
acSecModReadDef	dbSecReadDef
acSecModWriteDef	dbSecReplaceData
dbSecCreate	dbSecRetrieveData
dbSecDBAdmin	dbSecWriteSec
dbSecDBCreate	dbSecWriteDef
dbSecDBExclusive	dbSecWriteOwner
dbSecDBOpen
Note	The constants beginning with acSec are available to set database object permissions only using Visual Basic.


Event Procedure Constants

You can use the following constants with event procedures for the AfterDelConfirm event.

AfterDelConfirm Event Procedure Constants

acDeleteOK

acDeleteCancel

acDeleteUserCancel

You can use the following constants with event procedures for the BeforeDelConfirm event.

BeforeDelConfirm Event Procedure Constants

acDataErrContinue

acDataErrDisplay

You can use the following button mask constants with event procedures for the MouseDown, MouseUp, and MouseMove events.

Button Mask Constants

acLeftButton

acRightButton

acMiddleButton

You can use the following key mask constants with event procedures for the KeyDown, KeyUp, MouseDown, MouseUp, and MouseMove events.

Key Mask Constants

acShiftMask

acCtrlMask

acAltMask

You can use the following constants with event procedures for the NotInList event.

NotInList Event Procedure Constants

acDataErrAdded

acDataErrContinue

acDataErrDisplay

You can use the following constants with event procedures for the Error event.

Error Event Procedure Constants

acDataErrContinue

acDataErrDisplay

You can use the following constants with event procedures for the Updated event.

Updated Event Procedure Constants

acOLEChanged

acOLERenamed

acOLEClosed

acOLESaved


Action Constants

You can use these constants when you use Visual Basic to run a method of the DoCmd object. Using these constants with a method of the DoCmd object is the same as running the corresponding action in a macro.

DoCmd Object Constants
acAdd	acImportDelim	acRecordsMenu
acAll	acImportFixed	acRefresh
acAnywhere	acLast	acReport
acCopy	acLink	acSaveForm
acCurrent	acLinkDelim	acSaveFormAs
acCut	acLinkFixed	acSaveNo
acDelete	acLow	acSavePrompt
acDesign	acMacro	acSaveRecord
acDialog	acMedium	acSaveYes
acDown	acMenuCheck	acSearchAll
acDraft	acMenuGray	acSelectAllRecords
acEdit	acMenuUncheck	acSelection
acEditMenu	acMenuUngray	acSelectRecord
acEntire	acMenuVer1X	acShowAllRecords
acExit	acMenuVer20	acStart
acExport	acMenuVer70	acTable
acExportDelim	acModule	acToolbarNo
acExportFixed	acNew	acToolbarWhereApprop
acExportMerge	acNewRec	acToolbarYes
acFile	acNext	acUndo
acFirst	acNormal	acUp
acForm	acObject
acFormatRTF	acObjectUpdate
acFormatTXT	acObjectVerb
acFormatXLS	acPages
acFormBar	acPaste
acFormDS	acPreview
acGoTo	acPrevious
acHidden	acPrintAll
acHigh	acPrompt
acIcon	acQuery
acImport	acReadOnly


Miscellaneous Constants

The following tables list miscellaneous intrinsic constants provided by Microsoft Access.

You can use the following constants to fill a list box or combo box using a function.

List Box Constants
acLBClose	acLBGetRowCount
acLBEnd	acLBGetValue
acLBGetColumnCount	acLBInitialize
acLBGetColumnWidth	acLBOpen
acLBGetFormat
You can use the following constants with the SysCmd function.

SysCmd Function Constants
acObjStateDirty	acSysCmdInitMeter
acObjStateNew	acSysCmdRemoveMeter
acObjStateOpen	acSysCmdRuntime
acSysCmdAccessDir	acSysCmdSetStatus
acSysCmdAccessVer	acSysCmdUpdateMeter
acSysCmdClearStatus	acSysCmdProfile
acSysCmdGetObjectState	acSysCmdGetWorkgroupFile
acSysCmdIniFile	acSysCmdClearHelpTopic
You can use one of the following constants with the ControlType property and the CreateControl function to specify the control type:

ControlType and CreateControl Constants

acLabel	acPageBreak
acRectangle	acCustomControl
acLine	acToggleButton
acCommandButton	acDetail
acOptionButton	acHeader
acCheckBox	acFooter
acOptionGroup	acPageHeader
acBoundObjectFrame	acPageFooter
acTextBox	acGroupLevel1Header
acListBox	acGroupLevel1Footer
acComboBox	acGroupLevel2Header
acSubForm	acGroupLevel2Footer
acObjectFrame
The following table lists the OLE constants. Those constants marked with an asterisk can be used with the Action property.

OLE Constants
acOLEActivate *	acOLENone
acOLEActivateDoubleClick	acOLEPaste *
acOLEActivateGetFocus	acOLEPasteSpecialDlg *
acOLEActivateManual	acOLERenamed
acOLEChanged	acOLESaved
acOLEClose *	acOLESizeAutoSize
acOLEClosed	acOLESizeClip
acOLECopy *	acOLESizeStretch
acOLECreateEmbed *	acOLESizeZoom
acOLECreateFromFile	acOLEUpdate *
acOLECreateLink *	acOLEUpdateAutomatic
acOLECreateNew	acOLEUpdateFrozen
acOLEDelete *	acOLEUpdateManual
acOLEDisplayContent	acOLEVerbHide
acOLEDisplayIcon	acOLEVerbInPlaceActivate
acOLEEither	acOLEVerbInPlaceUIActivate
acOLEEmbedded	acOLEVerbOpen
acOLEFetchVerbs *	acOLEVerbPrimary
acOLEInsertObjDlg *	acOLEVerbShow
acOLELinked
The following table lists the constants you can use to specify or determine the state of the SpecialEffect property:

SpecialEffect Constants
acEffectChisled	acEffectRaised
acEffectEtched	acEffectShadow
acEffectNormal	acEffectSunken
The following table lists the constants you can use to specify or determine the state of the gridlines effect for an object in datasheet view:

Gridlines Constants
acGridlinesBoth	acGridlinesNone
acGridlinesBothV2	acGridlinesVert
acGridlinesHoriz


KeyCode Constants

You can use the following constants to represent keyboard values:

KeyCode Constants
vbKeyAdd	vbKeyF2	vbKeyNumPad3
vbKeyBack	vbKeyF3	vbKeyNumPad4
vbKeyCancel	vbKeyF4	vbKeyNumPad5
vbKeyCapital	vbKeyF5	vbKeyNumPad6
vbKeyClear	vbKeyF6	vbKeyNumPad7
vbKeyControl	vbKeyF7	vbKeyNumPad8
vbKeyDecimal	vbKeyF8	vbKeyNumPad9
vbKeyDelete	vbKeyF9	vbKeyPause
vbKeyDivide	vbKeyHelp	vbKeyPrint
vbKeyDown	vbKeyHome	vbKeyPrior
vbKeyEnd	vbKeyInsert	vbKeyRButton
vbKeyEscape	vbKeyLButton	vbKeyReturn
vbKeyExecute	vbKeyLeft	vbKeyRight
vbKeyF1	vbKeyMButton	vbKeySelect
vbKeyF10	vbKeyMenu	vbKeySeparator
vbKeyF11	vbKeyMultiply	vbKeyShift
vbKeyF12	vbKeyNext	vbKeySnapshot
vbKeyF13	vbKeyNumLock	vbKeySpace
vbKeyF14	vbKeyNumPad0	vbKeySubtract
vbKeyF15	vbKeyNumPad1	vbKeyTab
vbKeyF16	vbKeyNumPad2	vbKeyUp


RunSQL Action

You can use the RunSQL action to run a Microsoft Access action query using the corresponding SQL statement. You can also run a data-definition query.

Setting

The RunSQL action uses the following argument.

Action argument	Description

SQL Statement	The SQL statement for the action query or data-definition query you want to run. The maximum length of this statement is 256 characters. This is a required argument.

Remarks

You can use action queries to append, delete, and update records and to save a query's result set as a new table. You can use data-definition queries to create, alter, and delete tables, and to create and delete indexes. With the RunSQL action, you can perform these operations directly from a macro without having to use stored queries.

If you need to type an SQL statement longer than 256 characters, use the RunSQL method of the DoCmd object in Visual Basic instead. You can type SQL statements of up to 32,768 characters in Visual Basic.

Microsoft Access queries are actually SQL statements that are created when you design a query using the design grid in the Query window. The following table shows the Microsoft Access action queries and data-definition queries and their corresponding SQL statements.

Query type	SQL statement
Action
Append	INSERT INTO
Delete	DELETE
Make-table	SELECT...INTO
Update	UPDATE
Data-definition (SQL-specific)
Create a table	CREATE TABLE
Alter a table	ALTER TABLE
Delete a table	DROP TABLE
Create an index	CREATE INDEX
Delete an index	DROP INDEX
You can also use an IN clause with these statements to modify data in another database.

Note   To run a select query or crosstab query from a macro, use the View argument of the OpenQuery action to open an existing select query or crosstab query in Datasheet view. You can also run existing action queries and SQL-specific queries in the same way.

Tip   To see the SQL equivalent of a Microsoft Access query, click SQL on the View menu in the Query window. Use the listed SQL statements as models to create queries to run with the RunSQL action. Duplicating an SQL statement in the SQL Statement argument for the RunSQL action has the same effect as running this Microsoft Access query in the Query window.


TransferDatabase Action

You can use the TransferDatabase action to import or export data between the current Microsoft Access database and another database. You can also link a table to the current Microsoft Access database from another database. With a linked table, you have access to the table's data while the table itself remains in the other database.

Setting

The TransferDatabase uses the following arguments.

Action argument	Description

Transfer Type	The type of transfer you want to make. Select Import, Export, or Link in the Transfer Type argument in the Action Arguments section of the Macro window. The default is Import.

Database Type	The type of database to import from, export to, or link to. You can select Microsoft Access or one of a number of other database types in the Database Type argument. The default is Microsoft Access.

The database types shown in the Database Type argument depend on how you have set up Microsoft Access. Not all database types are installed by default. If the database type you want to use for importing, exporting, or linking isn't available, run the Microsoft Access Setup program, click the Add/Remove option, select the Data Access option in the dialog box and click the Change Option button, and then select the database type you want to install.

Database Name	The name of the database to import from, export to, or link to. Include the full path name. This is a required argument.

For types of databases that use separate files for each table, such as FoxPro, Paradox, and dBASE, enter the directory containing the file. Enter the filename in the Source argument (to import or link) or the Destination argument (to export).

For ODBC databases, type the full Open Database Connectivity (ODBC) connection string. To see an example of a connection string, link an external table to Microsoft Access using the Link Tables subcommand of the Get External Data command on the File menu. Open the table in Design view and view the table properties. The text before the first "-->" in the Description property setting is the connection string for this table.

For more information on ODBC connection strings, see the Help file or other documentation for the ODBC driver for this type of ODBC database.

Object Type	The type of object to import or export. If you select Microsoft Access for the Database Type argument, you can select Table, Query, Form, Report, Macro, or Module in the Object Type box. If you select any other type of database, or if you select Link in the Transfer Type box, this argument is ignored. The default is Table.

If you are exporting a select query to a Microsoft Access database, select Table in this argument to export the result set of the query, and select Query to export the query itself. If you are exporting a select query to another type of database, this argument is ignored and the result set of the query is exported.

Source	The name of the table, select query, or Microsoft Access object that you want to import, export, or link. For some types of databases, such as FoxPro, Paradox, or dBASE, this is a filename. Include the filename extension (such as .dbf) in the filename. This is a required argument.

Destination	The name of the imported, exported, or linked table, select query, or Microsoft Access object in the destination database. For some types of databases, such as FoxPro, Paradox, or dBASE, this is a filename. Include the filename extension (such as .dbf) in the filename. This is a required argument.

If you select Import in the Transfer Type argument and Table in the Object Type argument, Microsoft Access creates a new table containing the data in the imported table.

If you import a table or other object, Microsoft Access adds a number to the name if it conflicts with an existing name. For example, if you import Employees and Employees already exists, Microsoft Access renames the imported table Employees1.

If you export to a Microsoft Access database or another database, Microsoft Access automatically replaces any existing table or other object that has the same name.

Structure Only	Specifies whether to import or export only the structure of a database table without any of its data. Select Yes or No. The default is No.

Remarks

You can import and export tables between Microsoft Access and other types of databases. You can also export Microsoft Access select queries to other types of databases, as long as these select queries don't contain parameters. Microsoft Access exports the result set of the query in the form of a table. You can import and export any Microsoft Access database object if both databases are Microsoft Access databases.

If the database you're accessing requires a password, a dialog box is displayed when you run the macro. Type the password in this dialog box.

The TransferDatabase action is similar to clicking the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu of the Database window. You can use these commands to select a source of data, such as Microsoft Access or a type of database, spreadsheet, or text file. If you select a database, one or more dialog boxes are displayed in which you select the type of object to import or export (for Microsoft Access databases), the name of the object, and other options, depending on the database you are importing from or exporting or linking to. The arguments for the TransferDatabase action reflect the options in these dialog boxes.

If you want to supply index information for a linked FoxPro or dBASE table, first link the FoxPro or dBASE table by clicking the Link Tables subcommand of the Get External Data command on the File menu and specify the indexes in the dialog boxes for this command. Microsoft Access stores the index information in a special information (.inf) file, located in the Access folder. You can then delete the link to the linked table. The next time you use the TransferDatabase action to link this FoxPro or dBASE table, Microsoft Access uses the index information that you've specified.

To run the TransferDatabase action in Visual Basic, use the TransferDatabase method of the DoCmd object.


TransferSpreadsheet Action

You can use the TransferSpreadsheet action to import or export data between the current Microsoft Access database and a spreadsheet file. You can also link the data in a Microsoft Excel spreadsheet to the current Microsoft Access database. With a linked spreadsheet, you can view and edit the spreadsheet data with Microsoft Access while still allowing complete access to the data from your Microsoft Excel spreadsheet program.

Setting

The TransferSpreadsheet action uses the following arguments.

Action argument	Description

Transfer Type	The type of transfer you want to make. Select Import, Export, or Link in the Transfer Type argument in the Action Arguments section of the Macro window. The default is Import.

Spreadsheet Type	The type of spreadsheet to import from, export to, or link to. You can select one of a number of spreadsheet types in the box. The default is Microsoft Excel version 3.0.

Note   You can import, export, and link spreadsheet data from Microsoft Excel spreadsheets, but you can only import and export data from Lotus spreadsheets. Microsoft Access also no longer supports importing, exporting, or linking data from Lotus (WKS) or Microsoft Excel version 2.0 spreadsheets.

Table Name	The name of the Microsoft Access table to import spreadsheet data to, export spreadsheet data from, or link spreadsheet data to. You can also type the name of the Microsoft Access select query you want to export data from. This is a required argument.

If you select Import in the Transfer Type argument, Microsoft Access appends the spreadsheet data to this table if the table already exists. Otherwise, Microsoft Access creates a new table containing the spreadsheet data.

Filename	The name of the spreadsheet file to import from, export to, or link to. Include the full path. This is a required argument.

Microsoft Access creates a new spreadsheet when you export data from Microsoft Access. If the filename is the same as the name of an existing spreadsheet, Microsoft Access replaces the existing spreadsheet, unless you're exporting to a Microsoft Excel version 5.0 or 7.0 workbook. In that case, Microsoft Access copies the exported data to the next available worksheet in the workbook.

Has Field Names	Specifies whether the first row of the spreadsheet contains the names of the fields. If you click Yes, Microsoft Access uses the names in this row as field names in the Microsoft Access table when you import or link the spreadsheet data. If you click No, Microsoft Access treats the first row as a normal row of data. The default is No.

When you export Microsoft Access table or select query data to a spreadsheet, the field names are inserted into the first row of the spreadsheet if you have selected Yes for this argument.

If you want to import or link the Database named range from a Microsoft Excel spreadsheet, you must click Yes in this box.

Range	The range of cells to import or link. Leave this argument blank to import or link the entire spreadsheet. You can type the name of a range in the spreadsheet or specify the range of cells to import or link, such as A1:E25 or A1..E25. If you are importing from or linking to a Microsoft Excel version 5.0 or 7.0 worksheet, you can prefix the range with the name of the worksheet and an exclamation point; for example, Budget!A1:C7. Microsoft Access ignores this argument when you export.

If you are importing from or linking to a Microsoft Excel spreadsheet, you can specify the Database named range by typing DATABASE in the Range box. This name is reserved by Microsoft Access for this special named range in Microsoft Excel. For a description of specifying a range of cells as the Database named range in Microsoft Excel, see your Microsoft Excel documentation.

Remarks

You can export the data in Microsoft Access select queries to spreadsheets, as long as these select queries don't contain parameters. Microsoft Access exports the result set of the query, treating it just like a table.

Spreadsheet data that you append to an existing Microsoft Access table must be compatible with the table's structure. Each field in the spreadsheet must be of the same data type as the corresponding field in the table, and the fields must be in the same order (unless you set the Has Field Names argument to Yes, in which case the field names in the spreadsheet must match the field names in the table).

This action is similar to clicking the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu of the Database window. You can use these commands to select a source of data, such as Microsoft Access or a type of database, spreadsheet, or text file. If you select a spreadsheet, a series of dialog boxes appear, or a Microsoft Access wizard runs, in which you select the name of the spreadsheet and other options. The arguments of the TransferSpreadsheet action reflect the options in these dialog boxes or in the wizards.

To run the TransferSpreadsheet action in Visual Basic, use the TransferSpreadsheet method of the DoCmd object.


TransferText Action

You can use the TransferText action to import or export text between the current Microsoft Access database and a text file. You can also link the data in a text file to the current Microsoft Access database. With a linked text file, you can view and edit the text data with Microsoft Access while still allowing complete access to the data from your word processing program.

Setting

The TransferText action uses the following arguments.

Action argument	Description

Transfer Type	The type of transfer you want to make. You can import data from, export data to, or link to data in delimited or fixed-width text files. You can also export data to a Microsoft Word for Windows mail merge data file, which you can then use with the Word for Windows mail merge feature to create merged documents such as form letters and mailing labels.

Select Import Delimited, Import Fixed Width, Export Delimited, Export Fixed Width, Link Delimited, Link Fixed Width, or Export Word for Windows Merge in the Transfer Type argument in the Action Arguments section of the Macro window. The default is Import Delimited.

Specification Name	The specification name for the set of options that determines how a text file is imported, exported, or linked. This is a required argument for fixed-width text files.

You can use the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu to create a specification for a particular type of text file, such as a delimited text file that uses tabs to separate fields and has an MDY format for dates. When you click one of these commands and select a type of text file to import, export, or link, the Text Import Wizard, Text Export Wizard, or Link Text Wizard runs. You can click the Advanced button in the wizard and define and save a specification in the dialog box that is displayed. You can then type the specification name in this argument whenever you want to import or export the same type of text file.

You can import, export, or link delimited text files without typing a specification name for this argument. In this case, Microsoft Access uses the defaults from the wizard dialog box. Microsoft Access uses a predetermined format for mail merge data files, so you don't ever need to type a specification name for this argument when you export these types of files.

Table Name	The name of the Microsoft Access table to import text data to, export text data from, or link text data to. You can also type the name of the Microsoft Access select query you want to export data from. This is a required argument.

If you click Import Delimited or Import Fixed Width in the Transfer Type box, Microsoft Access appends the text data to this table if the table already exists. Otherwise, Microsoft Access creates a new table containing the text data.

File Name	The name of the text file to import from, export to, or link to. Include the full path. This is a required argument.

Microsoft Access creates a new text file when you export data from Microsoft Access. If the filename is the same as the name of an existing text file, Microsoft Access replaces the existing text file.

Has Field Names	Specifies whether the first row of the text file contains the names of the fields. If you click Yes, Microsoft Access uses the names in this row as field names in the Microsoft Access table when you import or link the text data. If you click No, Microsoft Access treats the first row as a normal row of data. The default is No.

Microsoft Access ignores this argument for Word for Windows mail merge data files because the first row must contain the field names.

When you export Microsoft Access table or select query data to a delimited or fixed-width text file, Microsoft Access inserts the field names of your table or select query into the first row of the text file if you have selected Yes for this argument.

If you are importing or linking a fixed-width text file and click Yes in this box, the first row containing the field names must use the field delimiter set in the import/export specification to separate the field names. If you are exporting to a fixed-width text file and click Yes for this argument, Microsoft Access inserts the field names into the first row of the text file using this delimiter.

Remarks

You can export the data in Microsoft Access select queries to text files, as long as these select queries don't contain parameters. Microsoft Access exports the result set of the query, treating it just like a table.

Text data that you append to an existing Microsoft Access table must be compatible with the table's structure. Each field in the text must be of the same data type as the corresponding field in the table, and the fields must be in the same order (unless you set the Has Field Names argument to Yes, in which case the field names in the text must match the field names in the table).

This action is similar to clicking the Import or Link Tables subcommand of the Get External Data command or the Save As/Export command on the File menu of the Database window. You can use these commands to select a source of data, such as Microsoft Access or a type of database, spreadsheet, or text file. If you select a delimited or fixed-width text file, a wizard prompts you to select the name of the text file and other options. The arguments of the TransferText action reflect the options in these wizards.

Tip   An import/export specification stores the information Microsoft Access needs to import, export, or link a text file. You can use stored specifications to import, export, or link text data from or to similar text files. For example, you might receive weekly sales figures in a text file from a mainframe computer. You can create and save a specification for this type of data and then use the specification whenever you add this data to your Microsoft Access database.

To run the TransferText action in Visual Basic, use the TransferText method of the DoCmd object.


DeleteObject Action

You can use the DeleteObject action within a macro to delete a specified database object.

Setting

The DeleteObject action uses the following arguments.

Action argument	Description

Object Type	The type of object to delete. Click Table, Query, Form, Report, Macro, or Module in the Object Type box in the Action Arguments section of the Macro window. To delete the object selected in the Database window, leave this box blank.

Object Name	The name of the object to delete. The Object Name box shows all objects in the database of the type selected by the Object Type argument. If you left the Object Type box blank, leave this box blank also.

If you run a macro containing the DeleteObject action in a library database, Microsoft Access will look for the object with this name first in the library database, then in the current database.

Warning   If you leave the Object Type and Object Name arguments blank, Microsoft Access will delete the object selected in the Database window without displaying a warning message when it encounters the DeleteObject action. To select an object in the Database window, you can use the SelectObject action with the In Database Window argument set to Yes.

Remarks

You can use the DeleteObject action to delete temporary objects you've created while running the macro. For example, you could use the OpenQuery action to run a make-table query that creates a temporary table. When you're finished using the temporary table, you can use the DeleteObject action to delete it.

This action has the same effect as selecting an object in the Database window and then pressing the DEL key or clicking Delete on the Edit menu. When you use the DeleteObject action, you don't need to select the object in the Database window, and Microsoft Access doesn't display a dialog box asking you to confirm the deletion.

To run the DeleteObject action in Visual Basic, you can use the DeleteObject method of the DoCmd object.


OutputTo Action

You can use the OutputTo action to output the data in the specified Microsoft Access database object (a datasheet, form, report, or module) to a file in Microsoft Excel (.xls) version 7.0, rich-text (.rtf), or MS-DOS Text (.txt) format.

Setting

The OutputTo action uses the following arguments.

Action argument	Description

Object Type	The type of object containing the data to output. Click Table (for a table datasheet), Query (for a query datasheet), Form (for a form or form datasheet), Report, or Module in the Object Type box in the Action Arguments section of the Macro window. You can't output a macro. If you want to output the active object, select its type with this argument, but leave the Object Name box blank. The default is Table. This is a required argument.

Object Name	The name of the object containing the data to output. The Object Name box shows all objects in the database of the type selected by the Object Type argument.

If you run a macro containing the OutputTo action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Output Format	The type of format you want used to output the data. You can click Microsoft Excel (*.xls), Rich Text Format (*.rtf), or MS-DOS Text (*.txt) in the box. Modules can be output only to MS-DOS Text format. If you leave this box blank, Microsoft Access prompts you for the output format.

Output File	The file you want to output the data to, including the full path. You can include the standard filename extension (.xls, .rtf, or .txt) for the output format you select by the Output Format argument, but it's not required. If you leave the Output File box blank, Microsoft Access prompts you for an output filename.

Auto Start	Indicator whether you want the appropriate application to start immediately after the OutputTo action runs, with the file specified in the Output File argument opened. If you select Yes, one of the following applications starts with the output file from the Microsoft Access object opened: Microsoft Excel (for .xls files), Microsoft Word for Windows (for .rtf files), or Microsoft Windows Notepad (for .txt files). If you select No, the application doesn't start. The default is No.

Remarks

The Microsoft Access data is output in the selected format and can be read by any application that uses the same format. For example, you can output a Microsoft Access report with its formatting to a rich-text format document and then open the document in Word for Windows.

The following rules apply when you use the OutputTo action to output a database object:

You can output data in table, query, and form datasheets. In the output file, all fields in the datasheet look as they do in Microsoft Access, except fields containing OLE objects. The columns for these fields are included in the output file, but the fields are blank.

For a control bound to a Yes/No field (a toggle button, option button, or check box), the output file displays the value -1 (Yes) or 0 (No).

If you output the data in a form in Form view, the output file always contains the form's Datasheet view.

If you output the data in a report, the only controls that are included in the output file are text boxes (for .xls output files) or text boxes and labels (for .rtf and .txt output files). All other controls are ignored. Header and footer information is also not included in the output file. The only exception to this is that when you output the data in a report to a Microsoft Excel file, a text box in a group footer containing an expression using the Sum function is included in the output file. No other control in a header or footer (and no aggregate function other than the Sum function) is included in the output file.

Subreports are included in the output file (for any of the output file formats), but subforms aren't.

If you output the data in a report to an output file and the columns and rows of data in the output file do not align as in the report, the following tips may help:

You can point to Size on the Format menu, then click To Fit to size the controls.

You can avoid overlapping controls or placing controls too close together.

You can point to Align on the Format menu, then click the appropriate command to align the controls on the report. Controls that are not aligned in the same row may be placed in separate rows, causing additional spacing.

The OutputTo action is similar to clicking Save As/Export on the File menu, selecting the To An External File Or Database option, and selecting the Save Formatted check box in the dialog box that is displayed. The action arguments correspond to the settings in the Save As/Export dialog boxes. The Save As/Export command, however, applies only to the object selected in the Database window. By using the OutputTo action, you can specify the object you want to output.

Note   You can output the selected data with the Save As/Export command. However, this functionality is not available with the OutputTo action.

You can also point to Office Links on the Tools menu, then click Analyze It With MS Excel or Publish It With MS Word to output a database object, and open the output file immediately in Microsoft Excel or Microsoft Word for Windows.

To run the OutputTo action in Visual Basic, use the OutputTo method of the DoCmd object.


SendObject Action

You can use the SendObject action to include the specified Microsoft Access datasheet, form, report, or module in an electronic mail message, where it can be viewed and forwarded. You can include objects in Microsoft Excel (.xls) version 7.0, rich-text (.rtf), or MS-DOS Text (.txt) format in messages for Microsoft Mail, Microsoft Windows for Workgroups mail, or another electronic mail application that uses the Microsoft Mail Applications Programming Interface (MAPI). If you have an electronic mail application that uses the Vendor Independent Mail (VIM) protocol and have installed and set up the dynamic-link library (Mapivim.dll) that converts MAPI mail messages to the VIM protocol, you can send Microsoft Access objects to the VIM mail application.

Setting

The SendObject action uses the following arguments.

Action argument	Description

Object Type	The type of object to include in the mail message. Click Table (for a table datasheet), Query (for a query datasheet), Form (for a form or form datasheet), Report, or Module in the Object Type box in the Action Arguments section of the Macro window. You can't send a macro. If you want to include the active object, select its type by this argument, but leave the Object Name box blank. The default is Table.

Object Name	The name of the object to include in the mail message. The Object Name box shows all objects in the database of the type selected by the Object Type argument. If you leave both the Object Type and Object Name boxes blank, Microsoft Access sends a message to the mail application without any database object.

If you run a macro containing the SendObject action in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Output Format	The type of format you want used for the included object. You can click Microsoft Excel (*.xls), Rich Text Format (*.rtf), or MS-DOS Text (*.txt) in the Output Format box. Modules can be sent only in MS-DOS Text format. If you leave this box blank, Microsoft Access prompts you for the output format.

To	The recipients of the message whose names you want to put on the To line in the mail message. If you leave this argument blank, Microsoft Access prompts you for the recipients' names.

Separate the recipients' names you specify in this argument and in the Cc and Bcc arguments with a semicolon (;) or with the list separator set in the Number tab of the Regional Settings properties sheet in the Windows Control Panel. If Microsoft Access can't identify the recipients' names, it doesn't send the message.

Cc	The recipients of the message whose names you want to put on the Cc ("carbon copy") line in the mail message. If you leave this box blank, the Cc line in the mail message is blank.

Bcc	The recipients of the message whose names you want to put on the Bcc ("blind carbon copy") line in the mail message. If you leave this box blank, the Bcc line in the mail message is blank.

Subject	The subject of the message. This text appears on the Subject line in the mail message. If you leave this box blank, the Subject line in the mail message is blank.

Message Text	Any text you want to include in the message in addition to the database object. This text appears in the main body of the mail message, after the object. If you leave this box blank, no additional text is included in the mail message. If you leave the Object Type and Object Name boxes blank, you can use this argument to send a mail message without a database object.

Edit Message	The indicator whether the message can be edited before it's sent. If you select Yes, the electronic mail application starts automatically, and the message can be edited. If you select No, the message is sent without providing a chance to edit the message. The default is No.

Remarks

The SendObject action is available only if you have a MAPI-compliant electronic mail application installed on your computer, or if you have a VIM-compliant electronic mail application and have installed and set up Mapivim.dll. For information on how to install and set up Microsoft Access support for VIM mail applications, see the Microsoft Office Resource Kit.

The object in the mail message is in the selected output format. When you double-click the object, the appropriate application starts with the object opened. The application for each type of output format is Microsoft Excel (for .xls files), Microsoft Word for Windows (for .rtf files), and Microsoft Windows Notepad (for .txt files).

The following rules apply when you use the SendObject action to include a database object in a mail message:

You can send table, query, and form datasheets. In the included object, all fields in the datasheet look as they do in Microsoft Access, except fields containing OLE objects. The columns for these fields are included in the object, but the fields are blank.

For a control bound to a Yes/No field (a toggle button, option button, or check box), the output file displays the value -1 (Yes) or 0 (No).

If you send a form in Form view, the included object always contains the form's Datasheet view.

If you send a report, the only controls that are included in the object are text boxes (for .xls files), or text boxes and labels (for .rtf and .txt files). All other controls are ignored. Header and footer information is also not included. The only exception to this is that when you send a report in Microsoft Excel format, a text box in a group footer containing an expression using the Sum function is included in the object. No other control in a header or footer (and no aggregate function other than Sum) is included in the object.

Subreports are included in the object (for any of the output formats), but subforms aren't.

If you send the data in a report and the columns and rows of data in the included object do not align as in the report, the following tips may help:

You can point to Size on the Format menu, then click To Fit to size the controls.

You can avoid overlapping controls or placing controls too close together.

You can point to Align on the Format menu, then click the appropriate command to align the controls on the report. Controls that are not aligned in the same row may be placed in separate rows, causing additional spacing.

The SendObject action has the same effect as clicking Send on the File menu, and the action arguments correspond to the settings in the Send dialog boxes.

Note   The Send command applies only to the active object. If you use the SendObject action, you can specify the object you want to send.

To run the SendObject action in Visual Basic, use the SendObject method of the DoCmd object.


ShowToolbar Action

You can use the ShowToolbar action to display or hide a built-in toolbar or a custom toolbar. You can display a built-in toolbar in all Microsoft Access windows or just the view in which the toolbar is normally displayed (for example, the Form view toolbar in Form view).

Setting

The ShowToolbar action uses the following arguments.

Action argument	Description

Toolbar Name	The name of the toolbar you want to display or hide. The Toolbar Name box shows all the built-in toolbars in Microsoft Access, followed by any custom toolbars you've defined in the current database. This is a required argument.

If the Allow Built-In Toolbars check box in the Startup dialog box (which is displayed when you click Startup on the Tools menu) is cleared, the Toolbar Name box shows only the custom toolbars you've defined, and you can use this action only to display and hide custom toolbars.

If you run a macro containing the ShowToolbar action in a library database, Microsoft Access looks for the toolbar with this name first in the library database, then in the current database.

Show	The indicator whether to display or hide the toolbar and in which views to hide or display it. The default is No (hide the toolbar).

For built-in toolbars, you can select Yes to display the toolbar in all Microsoft Access windows that become active, Where Appropriate to display the toolbar only in the view it's normally displayed in (as Microsoft Access does by default), or No to hide the toolbar in all Microsoft Access windows.

For custom toolbars, you can select Yes or Where Appropriate to display the custom toolbar in all Microsoft Access windows that become active or No to hide the toolbar in all Microsoft Access windows.

You can use this action in a macro with conditional expressions to display or hide one or more toolbars depending on certain conditions.

Remarks

If you want to show a particular toolbar on just one form or report, you can set the OnActivate property of the form or report to the name of a macro that contains a ShowToolbar action to show the toolbar. Then set the OnDeactivate property of the form or report to the name of a macro that contains a ShowToolbar action to hide the toolbar.

The ShowToolbar action has the same effect as clicking Toolbars on the View menu, and selecting or clearing a specific toolbar.

Note   The ShowToolbar action enables you to specify whether a built-in toolbar is displayed in all Microsoft Access windows or just the view in which it's normally displayed.

The built-in toolbars are also not available to display or hide using this action if you set the AllowBuiltInToolbars property to False (0) in Visual Basic, or if you set the Built-In Toolbars Available option to False in Visual Basic using the SetOption method.

To run the ShowToolbar action in Visual Basic, use the ShowToolbar method of the DoCmd object.


OpenModule Action

You can use the OpenModule action to open a specified Visual Basic module at a specified procedure. This can be a Sub procedure, a Function procedure, or an event procedure.

Setting

The OpenModule action uses the following arguments.

Action argument	Description

Module Name	The name of the module you want to open. You can leave this box blank if you want to search all the standard modules in the database for a procedure, and open the appropriate module at that procedure.

If you run a macro containing the OpenModule action in a library database, Microsoft Access looks for the module with this name first in the library database, then in the current database.

Procedure Name	The name of the procedure you want to open the module to. If you leave this box blank, the module opens to the Declarations section.

Note   You must enter a valid name in either the Module Name or Procedure Name argument.

Remarks

You can use this action to open an event procedure by specifying the event procedure in the Procedure Name argument. However, you must also specify a module name, because event procedures are private and don't appear in the global name space. For example, to open the Click event procedure of the PrintInvoice button on the form Orders, set the Module Name argument to Form.Orders and set the Procedure Name argument to PrintInvoice_Click. To view the event procedure for a form or report, the form or report must be open.

To open a private procedure, the module containing it must be open.

This action has the same effect as selecting a module in the Database window, and then pressing the Design button. This action also enables you to specify a procedure name and to search the standard modules in a database for procedures.

Tip   You can select a module in the Database window and drag it to a macro action row. This automatically creates an OpenModule action that opens the module to the Declarations section.

To run the OpenModule action in Visual Basic, use the OpenModule method of the DoCmd object.


Conditional Compilation

Conditional compilation enables you to run blocks of code selectively. You can use conditional compilation to run blocks of code containing debugging statements, to compare the speed of different approaches to the same programming task, or to localize your application for different languages.

You declare a compiler constant in code with the #Const directive, and you denote blocks of code to be conditionally compiled with the #If...Then...#Else directive. The following example runs debug code or production code, based on the value of the conDebug variable.

' Declare public compilation constant in Declarations section.

#Const conDebug = 1

Sub SelectiveExecution()

#If conDebug = 1 Then

.	' Run code with debugging statements.

.

.

#Else

.	' Run normal code.

.

.

#End If

End Sub


Custom Methods and Properties

In Microsoft Access, form and report modules are class modules. They act as templates for user-defined objects. When you create a new instance of a form or report class module, you create a user-defined object. Any public procedures defined within that module become methods and properties of the user-defined object. You can apply these methods, and set or return these properties using standard object syntax.

For example, the following code creates a custom filtering method for a Products form. This method constructs a criteria string, sets the Filter and FilterOn properties, and displays the form with filtered data, all in one step.

Sub SetFilter(strLetter As String)

strLetter = strLetter & "*"

Me.Filter = BuildCriteria("ProductName", dbText, strLetter)

Me.FilterOn = True

Me.Visible = True

End Sub

You can call this method from a procedure in a standard module. Use the New keyword to create an object variable and point it to a new instance of the Products form class module.

' Include in Declarations section of module.

Dim frm As New Form_Products

Sub FilterProducts()

frm.SetFilter "C"

End Sub

The new Property Let, Property Get, and Property Set statements enable you to define custom properties for a user-defined object. For example, the following code defines a property that enables you to change the color of a form's detail section to blue or red.

Static Property Let NewColor(strColor As String)

If strColor = "Blue" Then

Me.Section("Detail").BackColor = RGB(0, 0, 256)

ElseIf strColor = "Red" Then

Me.Section("Detail").BackColor = RGB(256, 0, 0)

Else

MsgBox "Set the NewColor property to Blue or Red."

End If

End Property

You can set this property with the following code in a standard module.

' Include in Declarations section of module.

Dim frm As New Form_Products

Sub ChangeColor()

frm.Visible = True

frm.NewColor = "Red"

End Sub


Named Arguments and Optional Arguments

When you call a Sub or Function procedure, you can supply arguments positionally, in the order they appear in the procedure's definition, or you can supply named arguments without regard to position.

For example, the following Sub procedure takes three arguments.

Sub PassArgs(strName As String, intAge As Integer, dteBirth As Date)

Debug.Print strName, intAge, dteBirth

End Sub

You can call this procedure by supplying its arguments in correct position, as in the next example.

PassArgs "Mary", 26, #2-21-69#

You can also call this procedure by supplying named arguments.

PassArgs intAge:=26, dteBirth:=#2/21/69#, strName:="Mary"

Note that when you supply a named argument, you separate the argument name and the argument with a colon (:) followed by an equal sign (=).

Optional arguments are preceded by the Optional keyword in the procedure definition. When you call a procedure with an optional argument, you can choose whether or not to specify the optional argument. An optional argument must always be passed as a Variant.

Named arguments are especially useful when you are calling a procedure that has optional arguments. If you use named arguments, you don't need to include commas (,) to denote missing positional arguments. Using named arguments makes it easier to keep track of which arguments you have passed and which you have omitted.

The following procedure includes an optional argument, the varCountry variable. The IsMissing function determines whether an optional argument has been passed to the procedure.

Sub OptionalArgs(strState As String, Optional varRegion As Variant, _

Optional varCountry As Variant)

If IsMissing(varRegion) And IsMissing(varCountry) Then

Debug.Print strState

ElseIf IsMissing(varCountry) Then

Debug.Print strState, varRegion

ElseIf IsMissing(varRegion) Then

Debug.Print strState, varCountry

Else

Debug.Print strState, varRegion, varCountry

End If

End Sub

You can call this procedure using named arguments as shown in the following examples.

OptionalArgs varCountry:="USA", strState:="MD"

OptionalArgs strState:= "MD", varRegion:="Mid-Atlantic"


Parameter Arrays

Parameter arrays enable you to pass an array of arguments to a procedure. You don't have to know the number of elements in the array when you define the procedure.

You can use the ParamArray keyword to denote a parameter array. The array must be declared as an array of Variants, and it must be the last argument in the procedure definition.

The following example shows how you might define a procedure with a parameter array.

Sub AnyNumberArgs(strName As String, ParamArray intScores() As Variant)

Dim intI As Integer

Debug.Print strName; "    Scores"

' Use UBound function to determine upper limit of array.

For intI = 0 To UBound(intScores())

Debug.Print "          "; intScores(intI)

Next intI

End Sub

You can call this procedure as shown in the following examples.

AnyNumberArgs "Jamie", 10, 26, 32, 15, 22, 24, 16

AnyNumberArgs "Kelly", "High", "Low", "Average", "High"


Performance Improvements in the Microsoft Jet Database Engine

The latest version of the Microsoft Jet database engine includes the following improvements.

A new index structure reduces the amount of storage space required by indexes, and reduces the amount of time required to create complex indexes. When you compact a database, its indexes are optimized for performance. You need to compact the database on a regular basis in order to maintain this optimization.

Indexed pages no longer contain read locks. As a result, performance is improved when several users are working with the same data at the same time in a multiuser database.

Operations that include the DELETE statement run faster. Portions of a page can be removed all at once, rather than row by row.

The Jet database engine's page allocation mechanism has been improved to increase the likelihood that data from the same table is stored on adjacent pages. As a result, the Jet database engine's read-ahead capability is enhanced.

The Jet database engine is multithreaded. By default, one thread performs read-ahead operations, one performs write-behind operations, and one performs cache maintenance.

Implicit transactions are built into the Jet database engine, so you can take advantage of the improved speed provided by transactions without using the BeginTrans and CommitTrans methods in your code. To retain full control over when data is written to disk, you should construct explicit transactions using the BeginTrans and CommitTrans methods.

The Jet database engine contains a new sorting mechanism to improve sorting performance.

The Jet database engine includes a dynamically configured cache that is allocated at start-up based on the amount of system memory available. The cache contains the most recently used data to enhance performance.

The Jet database engine provides new ISAM support for Excel 5.0 and 7.0, as well as text files, Lotus 1-2-3 version 3.0 spreadsheets, Paradox 5.x, dBASE 5.0, and FoxPro 3.0.


New and Enhanced Data Access Objects

The new Microsoft Jet database engine provides a new data access Errors collection. The Errors collection contains information about errors returned by a single data access operation. Since a data access operation can return more than one error, each error is represented by an Error object. When one or more errors have occurred, you can enumerate through the Errors collection to get information on each error.

Note   The data access Error object contains information on data access errors only. The Visual Basic Err object contains information on errors that have occurred in Visual Basic.


New and Enhanced Data Access Methods and Properties

The Microsoft Jet database engine supports the following new properties and methods for data access objects.

Properties	Methods
AbsolutePosition	CancelUpdate
AllPermissions	CopyQueryDef
ConflictTable	GetRows
DefaultPassword	MakeReplica
DefaultUser	NewPassword
DesignMasterID	Synchronize
DistinctCount
EditMode
HelpContext
HelpFile
Inherit
IniPath
KeepLocal
RecordsAffected
Replicable
ReplicaID


Using Data Access Objects in Microsoft Visual C++ Applications

Microsoft Visual C++ allows you to use data access objects (DAO). For specific information on writing Visual C++ applications using DAO, install the DAO Software Developer's Kit from the \DAOSDK directory of your Visual C++ disc (it is not installed in the default Visual C++ installation). The DAO Software Developer's Kit features a Help file that includes DAO, SQL, and Microsoft Jet database engine error information, as well as a set of code examples written in Visual C++ and a set of DAO classes to allow you to use DAO the same way you would use it in a Visual Basic program.


Using the Module Editor

The new module editor supports a fully customizable color-coded syntax in addition to text formatting options that you can set from the Module tab of the Options dialog, available by clicking Options on the Tools menu. The module editor also supports a line-continuation character, which enables you to continue a line of code across a line break. The line continuation character consists of a space followed by an underscore character (_), as in the following example.

MsgBox "You are about to delete 10 records.  " _

& "Do you want to continue?"

You can set a variety of other environment options from the Module tab of the Options dialog box. You can choose to view an entire module by selecting the Full Module View check box, or clear this box to view just one procedure at a time. You can provide command line arguments and conditional compilation arguments, and set other coding options, such as Break On All Errors and Require Variable Declaration.

For more information on a specific item in the Options dialog box, click [image] in the upper-right corner of the dialog box, and then click the item.

Several new features in the module editor are available to assist you in debugging your code. The Instant Watch dialog box provides you with the immediate value of a selected variable or expression. You can view this dialog box when your code is in break mode. Select a variable or expression and press SHIFT+F9, or click Instant Watch on the Tools menu.

Two other new commands, Set Next Statement and Show Next Statement, are available on the Run menu when your code has been halted. The Set Next Statement command enables you to move the point of execution to another statement, effectively skipping over portions of your code, or backing up and run certain statements again. The Show Next Statement command shows the next statement to be executed in the currently running code.

The new development environment provides End and Reset buttons, as well as the corresponding commands on the Run menu. When you end code execution by clicking the End button on the toolbar or by clicking the End button in the dialog box for a run-time error, module-level variables retain their values. To reset module-level variables, click the Reset button.


Using the Object Browser

The Object Browser is a tool that enables you to view members of an application's type library. From the Object Browser, you can also paste code into a module by selecting a method or property and clicking Paste. You can get help on any object, method, or property from within the Object Browser by selecting the name in the Methods/Properties box and clicking [image] in the lower section of the dialog box.

To view the Object Browser, open a module and click the Object Browser button on the toolbar, or click Object Browser on the View menu. You can also open the Object Browser by pressing F2 while in the module editor.

Information in a type library consists of definitions of class modules and standard modules. Class modules and standard modules are listed in the Modules/Classes box.

Classes in the Object Browser

A type library includes information about an application's objects as well as their methods and properties. Each object has an associated class definition where this information is maintained. The class definition provides a template for an object before that object is created in memory. In addition to classes representing objects in an application's object model, a type library includes classes that define controls.

For example, open the Object Browser while in a Module window and select "Access - Microsoft Access for Windows 95" in the Libraries/Databases box. This is the Microsoft Access type library. In the Modules/Classes box you will see all available Microsoft Access objects and controls. For example, select Application to view the methods and properties of the Application object listed in the Methods/Properties box. Or select CommandButton in the Modules/Classes box to view the methods and properties of a command button control.

The other classes that are visible in the Object Browser are form and report class modules. Like the classes for built-in objects and controls, form and report classes provide definitions for objects. These objects are defined by the user rather than by Microsoft Access. Within a form or report class module, you can define procedures that become methods and properties of that form when it is in Form view or that report when it is in Print Preview.

Form and report class modules are private to the database within which they reside, so procedures within them aren't available from any other database.

To view form and report class modules in the Object Browser, open the Northwind sample database, open the Object Browser, and select Northwind.mdb from the Libraries/Databases box. You'll see form and report modules listed for each form and report in the database, along with any public procedures defined within these modules.

Modules in the Object Browser

If a database includes Visual Basic modules, these modules and any public procedures defined within them also appear in the Modules/Classes box in the Object Browser. For example, open the Northwind sample database, open the Object Browser, and select Northwind.mdb from the Libraries/Databases box. Then select Utility Functions in the Modules/Classes box. The procedures defined in this standard module appear in the Methods/Properties box.

Public procedures defined in a Microsoft Access standard module are also available in the Object Browser from a referencing database. To view procedures in the Utility Functions module from another Microsoft Access database, you must first set a reference to the Northwind sample database from a second database.

Once you have set a reference to the Northwind sample database, open the Object Browser from the other database and choose Northwind.mdb from the Libraries/Databases box. You should see the Utility Functions module listed there, and all of its public procedures listed in the Methods/Properties box. You can call any of these referenced procedures from code running in the currently open database. Although, strictly speaking, these procedures are not methods or properties of an object, they are treated as such in the Object Browser, and you can call them from a referencing database using an object syntax.

For example, suppose you wish to call the IsLoaded function in the Utility Functions module in the Northwind sample database from the current database. You would call the function in one of the following ways.

' Fully qualified.

[Northwind.mdb].[Utility Functions].IsLoaded("Orders")

' Qualified by name of module.

[Utility Functions].IsLoaded("Orders")

' Not qualified.

IsLoaded("Orders")

Note   You should fully qualify the function call if there may be another module or function by the same name in another referenced database or a referenced Microsoft Visual Basic 4.0 project.


Setting References

OLE Automation enables you to use objects from other applications in Visual Basic code from Microsoft Access. An application that provides its objects for use by other applications also provides information about those objects in a type library. To achieve the best possible performance when using another application's objects, you should set a reference to that application's type library.

Some applications, including Microsoft Access, have a permanent type library that is stored in a separate file on your computer. A Microsoft Access database also has its own type library that is stored with the database, rather than in a separate file, and that applies only to that database. You can set a reference to either of these kinds of type libraries.

Setting a Reference to Another Application's Type Library

To set a reference to an application's type library:

1	Click References on the Tools menu.

2	Select the check boxes for those applications with type libraries you wish to reference.

If you are writing code that manipulates objects in another application, you should set a reference to that application's type library for best possible access to those objects. You don't need to set a reference to use another application's objects, but doing so provides several advantages for your application.

Your code will run faster if you set a reference to another application's type library before you work with its objects. If you have set a reference, you can declare an object variable representing an object in the other application as its most specific type. For example, if you are writing code to work with Microsoft Excel objects, you can declare an object variable of type Excel.Application using the following syntax only if you have created a reference to the Microsoft Excel type library. The code below is the fastest way to create a variable to represent the Microsoft Excel Application object.

Dim appXL As Excel.Application

If you have not set a reference to the Microsoft Excel type library, you must declare the variable as a generic variable of type Object. The following code runs more slowly.

Dim appXL As Object

Additionally, if you set a reference to an application's type library, all of its objects, as well as their methods and properties, are listed in the Object Browser. This makes it easy to determine what properties and methods are available to each object.

Since Microsoft Access is also an OLE Automation server, you can set a reference to its type library from another application, and control Microsoft Access objects from that application.

Setting a Reference to Another Database

Each individual Microsoft Access database has a type library that's saved with the database. You can set a reference from the current database to another Microsoft Access database and use Visual Basic procedures in that database. For example, the Northwind sample database includes a module named Utility Functions that contains a function called IsLoaded. You can set a reference to the Northwind sample database from the current database, and then call the IsLoaded function just as you would if it were defined within the current database.

To set a reference to the Northwind sample database from another database:

1	Open a module window.

2	Click References on the Tools menu, and click the Browse button in the References dialog box.

3	Select "Databases (*.mdb, *.mda)" from the Files Of Type box.

4	Locate the file Northwind.mdb. If you have installed this file, it should be in the \Msoffice\Access\Samples directory, unless you have moved it.

5	Click OK.

You should now see "Northwind.mdb" in the list of available references in the References dialog box.

Notes

Set a reference to another Microsoft Access database when you wish to call a public procedure that is defined within a standard module in that database. You can't call procedures that are defined within a form or report module or that are preceded with the Private keyword.

From another application, such as Microsoft Visual Basic or Microsoft Excel, you can set a reference to the Microsoft Access type library. However, you can set a reference to an individual Microsoft Access database only from another Microsoft Access database.

If you set a reference to a type library from Microsoft Access, then move the file that contains that type library to a different directory, Microsoft Access will attempt to locate the file and re-establish the reference. If the RefLibPaths key exists in the registry, Microsoft Access will first search there. If there's no matching entry, Microsoft Access will search for the file first in the current directory, then in all the directories on the drive. You can create the RefLibPaths key using the registry editor in Windows, under the registry key \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Access\7.0. For more information about using the registry editor, see the Windows documentation.


Using the Debug Window

The Debug window in Microsoft Access for Windows 95 consists of two panes [image] an Immediate pane that functions much like the Immediate window in previous versions of Microsoft Access, and a Watch pane. The Watch pane is visible only if you have set a watch expression.

To view the Debug window, open a module and click the Debug window button on the toolbar. You can also open the Debug window by pressing CTRL+G when working in the module editor.

You can run any Sub or Function procedure, including event procedures, in the Immediate pane.

In previous versions of Microsoft Access, if a form or report module was the active window, you could run a procedure defined in that form or report from the Immediate window by simply typing the name of the procedure. In Microsoft Access 95, you must qualify the procedure with the class name of the form or report. The following example, when typed in the Immediate pane of the Debug window, runs a ListNames procedure that is defined in an Employees form.

Form_Employees.ListNames

To run an event procedure in a form module from the Debug window, you must also verify that the form is in Form view. The following example runs the event procedure for a command button named PersonalInfo on an Employees form.

Form_Employees.PersonalInfo_Click

The Watch pane enables you to view the value of an expression or a variable while code is running. To set a watch expression, click Add Watch on the Tools menu.

The new Debug window automatically provides status information about your code. When no code is running, the status bar at the top of the Debug window displays "<Ready>". Once code begins executing, the status bar displays the name of the current database, the module in which the procedure that is executing resides, and the name of the procedure itself.

You can also view the Calls window from the Debug window by clicking [image].


What's New for Developers: Programming with Forms and Reports

In previous versions of Microsoft Access, form modules and report modules were similar to standard modules. The primary differences between the two were that form and report modules were associated with individual forms and reports, while standard modules were not associated with any object. Also, form and report modules contained event procedures to respond to events occurring on the form or report.

In Microsoft Access for Windows 95, form modules and report modules are class modules. A class module can be thought of as a template for a user-defined object that is based on a form or report. Within a class module you can add public procedures that define custom methods and properties for the object.

Creating an Instance of a Form

When you open a form in Form view, whether from the user interface or from Visual Basic, you create an instance of that form. In other words, you designate space in memory where the object now exists, and you can then call its methods and set or return its properties from code, as you would for any built-in object. The same is true when you open a report in Print Preview.

When you refer to a form in Visual Basic code, you are usually working with the default instance of the form. A form has only one default instance. You can also create multiple instances of the same form from Visual Basic. When you create multiple instances of a form, you create non-default instances.

Creating the Default Instance of a Form

There are four ways to create the default instance of a form. You can open an existing form by using the user interface, by executing the OpenForm method of the DoCmd object, by calling the CreateForm function and switching the new form into Form view, or by creating with Visual Basic a variable of type Form to refer to the default instance. The following example opens an Employees form and points a Form variable to it.

Dim frm As Form

DoCmd.OpenForm "Employees"

Set frm = Forms!Employees

Microsoft Access also provides a new shortcut that enables you to open a form and refer to a method or property of that form or one of its controls in one step. You refer to the form's class module as shown in the following example.

Form_Employees.Visible = True

Form_Employees.Caption = "New Employees"

When you run this code, Microsoft Access opens the Employees form in Form view if it's not already open and displays the caption. The form is not visible until you explicitly set its Visible property to True (-1). When the procedure that calls this code has finished executing, the instance of the form is destroyed [image] that is, the form is closed.

If you try to run this code when the Employees form is open in Design view, Microsoft Access generates a run-time error. The form must be either open in Form view or not open at all.

If you use this syntax to change a property of the form or one of its controls, that change is lost when the instance of the form is destroyed. This holds true any time you change a property setting for a form in Form view. You must change the property in Design view and save the change with the form.

Creating Multiple Non-Default Instances of Forms

You can create multiple non-default instances of forms if you wish to display more than one instance of a form at a time. For example, you might want to display the records for an employee and the employee's manager at the same time. You can create one instance of the Employees form to display the employee's record, and one to display the manager's record.

To create new, non-default instances of a form from Visual Basic, declare a variable for which the type is the class name of the form module. You must include the New keyword in the variable declaration. For example, the following code creates a new instance of the Employees form and assigns it to a Form variable.

Dim frm As New Form_Employees

This non-default instance of the form isn't visible until you explicitly set its Visible property.

When the procedure that creates this instance has finished executing, the instance is destroyed unless you have declared the variable representing it as a module-level variable. Since module-level variables retain their values until they are reset with the Reset command on the Run menu or the Reset button on the toolbar, the form will stay open if the variable has been declared as a module-level variable.

Any properties that you set will affect this instance of the form, but will not be saved with the form. Also, a new instance of the form cannot be created if the form is open in Design view.

A non-default instance of a form can't be referred to by name in the Forms collection. You can refer to it by index number only. Since you can create multiple non-default instances of a form, and each instance has the same name, you can have more than one form with the same name in the Forms collection, without any means of distinguishing them other than by index number.


Using Microsoft Access as an OLE Automation Controller

As an OLE Automation controller, Microsoft Access can manipulate any object in another application's type library. Examples of applications that expose their objects as OLE Automation servers include Microsoft Excel, Microsoft Word, and Microsoft Project, and some applications created with Microsoft Visual Basic 4.0. Check your application's documentation to determine whether it can function as an OLE Automation server.

In Microsoft Access 2.0, you could use the CreateObject function or the GetObject function to point a variable to an instance of an application. In Microsoft Access for Windows 95, you can also use the New keyword to create a new instance of some applications. Check your application's documentation to determine which syntax it supports.

In Microsoft Access, you can set a reference to an application's type library to improve performance when you control that application through OLE Automation. Microsoft Access also includes the Object Browser, a tool that enables you to view objects in another application's type library, as well as their methods and properties.


Using Microsoft Access as an OLE Automation Server

Microsoft Access provides its own objects for use by other applications. From any application that acts as an OLE Automation controller, you can launch Microsoft Access and manipulate its objects. Some applications that act as OLE Automation controllers include recent versions of Microsoft Visual Basic, Microsoft Visual C++, Microsoft Excel, and Microsoft Project. Additionally, you can use Microsoft Access as an OLE Automation controller to manipulate another instance of Microsoft Access that is acting as an OLE Automation server.

The Microsoft Access type library provides information about Microsoft Access objects to other applications. You can set a reference to the Microsoft Access type library from an OLE Automation controller, and view its objects in the Object Browser.

Microsoft Access includes the Microsoft Jet database engine, which provides data access objects. Data access objects exist in a separate type library, the DAO Object Library. The Jet database engine doesn't stand on its own, but must be hosted by another application, such as Microsoft Access. If you wish to control data access objects through OLE Automation from another application, you can use the DBEngine property of the Microsoft Access Application object to access objects in the DAO Object Library.

Whether you want to manipulate Microsoft Access objects, data access objects, or both in order to do so through OLE Automation, you must create an instance of the Microsoft Access Application object. For example, suppose you want to display data from Microsoft Excel in a Microsoft Access form or report. To launch Microsoft Access from Microsoft Excel, you can use the CreateObject function to create an instance of the Microsoft Access Application object. You can also use the GetObject function to point an object variable to an existing instance of Microsoft Access.

Note   Some applications, such as Microsoft Visual Basic 4.0, allow you to use the New keyword to create an instance of Microsoft Access. You can also use the New keyword from Microsoft Access itself to create another instance of Microsoft Access. Check your application's documentation to determine whether it supports this syntax.

Once you have launched an instance of Microsoft Access, if you want to control any Microsoft Access objects, you must open a database in the Microsoft Access window by using either the OpenCurrentDatabase method or the NewCurrentDatabase method. If you've opened Microsoft Access only as a means to use data access objects, then you don't need to open a database in the Microsoft Access window.


What's New for Developers: Changes in Scope and Visibility

Microsoft Access for Windows 95 has a slightly different scoping paradigm than previous versions of Microsoft Access. A procedure or variable may be either public or private. Private procedures and variables are available only from within the module in which they reside. Public procedures and variables are available to all procedures in the database.

Procedures

By default, all procedures, including the Sub, Function, and Property procedures, are public. Event procedures are an exception [image] Microsoft Access automatically precedes event procedures with the Private keyword.

Public procedures defined in a standard module are available to referencing databases in addition to the current database. These procedures will be available in the Object Browser from the referencing database. Public procedures defined in a form module or report module are available only to the current database.

Variables

Variables declared within a procedure are private to that procedure and can't be made public. A variable declared at the module level is by default private to that module. To declare a module-level variable available to all procedures in the database, precede it with the Public keyword.

Public variables defined in a standard module are available to referencing databases, but they aren't available in the Object Browser. You can, however, still refer to them in code from a referencing database. Public variables defined in a form module or report module are never visible outside the current database.

Constants follow the same scoping rules as variables.

Procedure-level variables lose their values once the procedure has finished running, unless they are declared as Static. Static variables retain their values between procedures, but lose their values when all code in the call tree has finished executing. A module-level variable declared in a standard module retains its value even after all code has finished executing. Module-level variables in standard modules don't lose their values until you reset them by clicking Reset on the Run menu or clicking the Reset button on the toolbar, or until you close the database.

Form modules and report modules in Microsoft Access are class modules. Module-level variables declared in a form or report module exist in memory whenever the form is in Form view or the report is in Print Preview. They are destroyed when the form or report is closed, or when it's returned to form Design view or report Design view.


What's New for Developers: Improvements in Compilation Performance

Microsoft Access includes improvements to module loading and compilation performance to make your code compile and run faster.

The Compile All Modules and Compile Loaded Modules commands are available on the Run menu. The Compile All Modules command compiles all modules in the database, whether or not they are currently loaded. The Compile Loaded Modules command compiles only currently loaded modules.

To save all code in the database in its fully compiled state, you should open the database in Exclusive mode, click Compile All Modules on the Run menu, and then click Save All Modules on the File menu.

By default, Microsoft Access compiles on demand. This means that if you don't explicitly compile your code before running it, Microsoft Access will load only part of the potential call tree.

You can turn off this default by clearing Compile On Demand on the Module tab of the Options dialog box, available by clicking Options on the Tools menu. When this option is cleared, Microsoft Access will compile the entire call tree for the module from which code is being run.

When you click Compile Loaded Modules on the Run menu, only currently loaded modules will be compiled, regardless of the setting of the Compile On Demand option.


ApplyFilter Event

The ApplyFilter event occurs when the user does one of the following:

Clicks the Apply Filter/Sort command on the Filter menu, or clicks the Apply Filter button on the toolbar. This applies the most recently created filter (created using either the Filter By Form feature or the Advanced Filter/Sort window).

Clicks the Filter By Selection subcommand of the Filter command on the Records menu, or clicks the Filter By Selection button on the toolbar. This applies a filter based on the current selection in the form.

Clicks the Remove Filter/Sort command on the Records menu, or clicks the Remove Filter button on the toolbar. This removes any filter (or sort) currently applied to the form.

Closes the Advanced Filter/Sort window or the Filter By Form window.

Remarks

You can use the ApplyFilter event to:

Make sure the filter that is being applied is correct. For example, you may want to be sure that any filter applied to an Orders form includes criteria restricting the OrderDate field. To do this, check the value of the Filter property for the form to make sure this criteria is included in the WHERE clause expression in this property.

Change the display of the form before the filter is applied. For example, when you apply a certain filter, you may want to disable or hide some fields that are not appropriate for the records displayed by this filter.

Undo or change actions you took when the Filter event occurred. For example, you can disable or hide some controls on the form when the user is creating the filter, because you do not want these controls to be included in the filter criteria. You can then enable or show these controls after the filter is applied.

The actions in the ApplyFilter macro or event procedure occur before the filter is applied or removed; or after the Advanced Filter/Sort or Filter By Form window is closed, but before the form is redisplayed. The criteria you've entered in the newly created filter are available to the ApplyFilter macro or event procedure (as the setting of the Filter property).

Note   The ApplyFilter event does not occur when you apply or remove a filter using the ApplyFilter, OpenForm, or ShowAllRecords actions in a macro, or their corresponding methods of the DoCmd object in Visual Basic. It also does not occur if you use the Close action or the Close method of the DoCmd object to close the Advanced Filter/Sort window or the Filter By Form window. The ApplyFilter event also does not occur if you set the Filter property or FilterOn property in a macro or Visual Basic (although you can set these properties in an ApplyFilter macro or event procedure).


ApplyFilter Event - Macros
ApplyFilter Event — Macros

To run a macro when the ApplyFilter event occurs, set the OnApplyFilter property to the name of the macro.

Remarks

You can check a filter, or even change the criteria the user has entered, by reading the value of the Filter property in a macro condition, or setting the value of the property using the SetValue action in an ApplyFilter macro.

You can use the CancelEvent action in an ApplyFilter macro to cancel applying the filter. You can use a condition to check the value of one or more controls on the form, and apply a filter only when appropriate. For example, if a HasOutstandingOrders check box is selected in an Orders form, you could apply a filter to show these outstanding orders in the records on the form. Otherwise, you can cancel applying the filter, and display a message saying there are no outstanding orders to display.


ApplyFilter Event - Event Procedures
ApplyFilter Event — Event Procedures

To create an event procedure that is executed when the ApplyFilter event occurs, set the OnApplyFilter property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)

The ApplyFilter event procedure uses the following arguments.

Argument	Description
Cancel	The setting determining whether to apply the filter. Setting Cancel to True (-1) prevents the filter from being applied. You can also use the CancelEvent method of the DoCmd object to cancel applying the filter.
ApplyType	The action you took that caused the ApplyFilter event to occur. The ApplyType argument can be one of the following intrinsic constants: Constant Value acShowAllRecords 0 acApplyFilter 1 acCloseFilterWindow 2
Remarks

You can use the ApplyFilter event procedure to show or hide, enable or disable certain controls on the form when the filter is applied or removed. For example, when a filter is applied to an Orders form to show only orders that have been paid for, you can hide the AmountDue, Tax, and TotalDue fields when the ApplyType argument is acApplyFilter, and show them again when the ApplyType argument is acShowAllRecords.

You can also use the ApplyFilter event procedure to undo actions you took when the Filter event occurred. This is especially useful if the user closed the filter window without creating a filter (the ApplyType argument is acCloseFilterWindow).


ApplyFilter Event - Event Procedures Example
ApplyFilter Event — Event Procedures Example

The following example shows how to hide the AmountDue, Tax, and TotalDue controls on an Orders form when the applied filter restricts the records to only those orders that have been paid for.

Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)

If Not IsNull(Me.Filter) And (InStr(Me.Filter, "Orders.Paid=-1")>0 _

Or InStr(Me.Filter, "Orders.Paid=True")>0)Then

If ApplyType = acApplyFilter Then

Forms!Orders!AmountDue.Visible = False

Forms!Orders!Tax.Visible = False

Forms!Orders!TotalDue.Visible = False

ElseIf ApplyType = acShowAllRecords Then

Forms!Orders!AmountDue.Visible = True

Forms!Orders!Tax.Visible = True

Forms!Orders!TotalDue.Visible = True

End If

End If

End Sub


Filter Event

The Filter event occurs when the user does one of the following:

Clicks the Filter By Form subcommand of the Filter command on the Records menu, or clicks the Filter By Form button on the toolbar. This opens the Filter By Form window, where you can quickly create a filter based on the fields in the form.

Clicks the Advanced Filter/Sort subcommand of the Filter command on the Records menu. This opens the Advanced Filter/Sort window, where you can create complex filters for the form.

Remarks

You can use the Filter event to:

Remove any previous filter for the form. To do this, set the Filter property of the form to a zero-length string (" ") in the Filter macro or event procedure. This is especially useful if you want to make sure extraneous criteria do not appear in the new filter. For example, whenever you use the Filter By Selection feature, the criteria you use (the selected text in the form) is added to the Filter property WHERE clause expression, and appears in both the Filter By Form window and the Advanced Filter/Sort window. You can remove this old criteria using the Filter event.

Enter default settings for the new filter. To do this, set the Filter property to include these criteria. For example, you may want all filters for a Products form to display only current products (products for which the Discontinued control in the Products form is not selected).

Use your own custom filter window instead of one of the Microsoft Access filter windows. When the Filter event occurs, you can open your own custom form and use the entries on this form to set the Filter property and filter the original form. When the user closes this custom form, set the FilterOn property of the original form to True to apply the filter. Canceling the Filter event prevents the Microsoft Access filter window from opening.

Prevent certain controls on the form from appearing or being used in the Filter By Form window. If you hide or disable a control in the Filter macro or event procedure, the control is hidden or disabled in the Filter By Form window, and can't be used to set filter criteria. You can then use the ApplyFilter event to show or enable this control after the filter is applied, or when the filter is removed from the form.


Filter Event - Macros
Filter Event — Macros

To run a macro when the Filter event occurs, set the OnFilter property to the name of the macro.

Remarks

You can set the Filter property in a Filter macro using the SetValue action. This enables you to customize the filter criteria that the user sees when the Filter By Form window or Advanced Filter/Sort window is displayed.

You can use the CancelEvent action in a Filter macro to cancel opening the filter window.


Filter Event - Event Procedures
Filter Event — Event Procedures

To create an event procedure that is executed when the Filter event occurs, set the OnFilter property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Filter(Cancel As Integer, FilterType As Integer)

The Filter event procedure uses the following arguments.

Argument	Description
Cancel	The setting determining whether to open the filter window. Setting Cancel to True (-1) prevents the filter window from opening. You can also use the CancelEvent method of the DoCmd object to cancel opening the filter window.
FilterType	The filter window the user is trying to open. The FilterType argument can be one of the following intrinsic constants: Constant Value acFilterByForm 0 acFilterAdvanced 1
Remarks

You can use the Filter event procedure to disable or hide certain controls in the Filter By Form window, preventing them from being used in filter criteria. For example, you may always want your Orders form to show records that have a value in the TotalDue control, no matter how small. You can disable or hide this control in the Filter event procedure, then enable or show it in the ApplyFilter event procedure. Disabling and hiding controls in the Filter By Form window is best accomplished in the Filter event procedure rather than the Filter macro, because you can check the FilterType argument to see if the user opened the Filter By Form window. All of the fields in a form appear in the Advanced Filter/Sort window, even if the controls are disabled or hidden.


Filter Event - Event Procedures Example
Filter Event — Event Procedures Example

The following example shows how to disable the TotalDue control on an Orders form when the user tries to create a filter, so that the user can't filter on this field. Any records that have a TotalDue value and meet the other filter criteria will always be shown on the filtered form. This example also forces the user to use the Filter By Form window and not the Advanced Filter/Sort window.

Private Sub Form_Filter(Cancel As Integer, FilterType As Integer)

If FilterType = acFilterByForm Then

Forms!Orders!TotalDue.Enabled = False

ElseIf FilterType = acFilterAdvanced Then

MsgBox "The best way to filter this form is to use the " & _

"Filter By Form command or toolbar button.", vbOKOnly + vbInformation

Cancel = True

End If

End Sub


NoData Event

The NoData event occurs after Microsoft Access formats a report for printing that has no data (the report is bound to an empty recordset), but before the report is printed. You can use this event to cancel printing of a blank report.

Remarks

If the report is not bound to a table or query (using the report's RecordSource property), the NoData event does not occur.

This event occurs after the Format events for the report, but before the first Print event.

This event does not occur for subreports. If you want to hide controls on a subreport when the subreport has no data, so that the controls don't print in this case, you can use the HasData property in a macro or event procedure that runs when the Format or Print event occurs.

The NoData event occurs before the first Page event for the report.


NoData Event - Macros
NoData Event — Macros

To run a macro when the NoData event occurs, set the OnNoData property to the name of the macro.

Remarks

You can use the CancelEvent action in a NoData macro to cancel printing of the blank report.


NoData Event - Event Procedures
NoData Event — Event Procedures

To create an event procedure that is executed when the NoData event occurs, set the OnNoData property to [Event Procedure], and click the Build button.

Syntax

Private Sub Report_NoData(Cancel As Integer)

The NoData event procedure uses the following argument.

Argument	Description
Cancel	The setting determining whether to print the report. Setting Cancel to True (-1) prevents the report from printing. You can also use the CancelEvent method of the DoCmd object to cancel printing the report.


NoData Event - Event Procedures Example
NoData Event — Event Procedures Example

The following example shows how to cancel printing a report when it is blank. A message box notifying the user that the printing has been canceled is also displayed.

Private Sub Report_NoData(Cancel As Integer)

MsgBox "The report has no data." & _

"@Printing the report is canceled. " & _

"@Check the source of data for the report to make sure you " & _

"entered the correct criteria (for example, a valid range " & _

"of dates).", vbOKOnly + vbInformation

Cancel = True

End Sub


Page Event

The Page event occurs after Microsoft Access formats a page of a report for printing, but before the page is printed. You can use this event to draw a border around the page, or add other graphic elements to the page.

Remarks

This event occurs after all the Format events for the report, and after all the Print events for the page, but before the page is actually printed.

You normally use the Line, Circle, or PSet methods in the Page event procedure to create the desired graphics for the page.

The NoData event occurs before the first Page event for the report.


Page Event - Macros
Page Event — Macros

To run a macro when the Page event occurs, set the OnPage property to the name of the macro.

Remarks

Since you normally use the Line, Circle, or PSet methods in the Page event procedure to create the desired graphics for the page, you typically use the Page event procedure with this event rather than the Page macro.

You can't use the CancelEvent action in a Page macro.


Page Event - Event Procedures
Page Event — Event Procedures

To create an event procedure that is executed when the Page event occurs, set the OnPage property to [Event Procedure], and click the Build button.

Syntax

Private Sub Report_Page( )

Remarks

You can't cancel the Page event.


Page Event - Event Procedures Example
Page Event — Event Procedures Example

The following example shows how to draw a rectangle around a report page, using the Line method. The ScaleWidth and ScaleHeight properties by default return the internal width and height of the report.

Private Sub Report_Page()

Me.Line(0, 0)-(Me.ScaleWidth, Me.ScaleHeight), , B

End Sub


 Command Function

You can use the Command function to return the argument portion of the command line used to launch Microsoft Access.

Syntax

Command

Remarks

When Microsoft Access is launched from the command line, any portion of the command line that follows the /Cmd option is passed to the program as the command-line argument. You can use the Command function to return the argument that has been passed.

To change a command-line argument once a database has been opened, click Options on the Tools menu. On the Module tab of the Options dialog box, enter a new argument in the Command Line Arguments box. The Command function will now return the new argument you have entered.

When the Command function is used anywhere other than in Visual Basic code in a module, you must include empty parentheses after the function. For example, to use the Command function in a text box on a form, you would set the ControlSource property to an expression like the following.

= Command()


Command Function Example

The following example shows how to launch Microsoft Access with a command-line argument, then shows how to return the value of this argument using the Command function.

To test this example, click the Windows Start Menu and choose Run. Type the following in the Run dialog box, on a single line.

C:\Msoffice\Access\Msaccess.exe C:\Msoffice\Access\Samples\Northwind.mdb /cmd "Orders"

Next, open a new module in the Northwind sample database and add the following function.

Function CheckCommandLine()

' Check value returned by Command function.

If Command = "Orders" Then

DoCmd.OpenForm "Orders"

ElseIf Command = "Employees" Then

DoCmd.OpenForm "Employees"

Else

Exit Function

End If

End Function

When you call this function, Microsoft Access will open the Orders form.

You can create a macro named AutoExec to call this function automatically when the database is opened. For more information on calling an action when a database opens, see Carry out an action when my database first opens.


CurrentDb Function

The CurrentDb function returns an object variable of type Database that represents the database currently open in the Microsoft Access window.

Syntax

CurrentDb

Remarks

In order to manipulate the structure of your database and its data from Visual Basic, you must use data access objects. The CurrentDb function provides a way to access the current database from Visual Basic code without having to know the name of the database. Once you have a variable that points to the current database, you can also access and manipulate other objects and collections in the data access object hierarchy.

You can use the CurrentDb function to create multiple object variables that refer to the current database. In the following example, the variables dbsA and dbsB both refer to the current database.

Dim dbsA As Database, dbsB As Database

Set dbsA = CurrentDb

Set dbsB = CurrentDb

Note   In previous versions of Microsoft Access, you may have used the syntax DBEngine.Workspaces(0).Databases(0) or DBEngine(0)(0) to return a pointer to the current database. In Microsoft Access for Windows 95, you should use the CurrentDb function instead. The CurrentDb function creates another instance of the current database, while the DBEngine(0)(0) syntax refers to the open copy of the current database. Using the CurrentDb function enables you to create more than one variable of type Database that refer to the current database. Microsoft Access still supports the DBEngine(0)(0) syntax, but you should consider making this modification to your code in order to avoid possible conflicts in a multiuser database.

If you need to work with another database at the same time that the current database is open in the Microsoft Access window, use the OpenDatabase method of a Workspace object. The OpenDatabase method doesn't actually open the second database in the Microsoft Access window; it simply returns a Database variable representing the second database. The following example returns a pointer to the current database and to a database called Contacts.mdb.

Dim dbsCurrent As Database, dbsContacts As Database

Set dbsCurrent = CurrentDb

Set dbsContacts = DBEngine.Workspaces(0).OpenDatabase("Contacts.mdb")


CurrentDb Function Example

The following example uses the CurrentDb function to return a Database object variable pointing to the current database. It then enumerates all the fields in the Employees table in that database.

Sub ListFields()

Dim dbs As Database, tdf As TableDef, fld As Field

' Return Database object variable pointing to current database.

Set dbs = CurrentDb

' Return TableDef object variable pointing to Employees table.

Set tdf = dbs.TableDefs!Employees

' Enumerate fields in Employees table.

For Each fld In tdf.Fields

Debug.Print fld.Name

Next fld

End Sub


LoadPicture Function

The LoadPicture function loads a graphic into a custom control.

Syntax

LoadPicture(stringexpression)

The LoadPicture function uses the following argument.

Argument	Description

stringexpression	The filename of the graphic to be loaded. The graphic can be a bitmap file (.bmp), icon file (.ico), run-length encoded file (.rle), or metafile (.wmf).

Remarks

Assign the return value of the LoadPicture function to the Picture property of a custom control to dynamically load a graphic into the control. The following example loads a bitmap into a control called OLECustomControl on an Orders form.

Set Forms!Orders!OLECustomControl.Picture = LoadPicture("Stars.bmp")

The LoadPicture function returns an object of type Picture. You can assign this value to a variable of type Object using the Set statement.

The Picture object is not a Microsoft Access object, but it is available to procedures in Microsoft Access. If you wish to assign the return value of the LoadPicture function to an object variable of type Picture, you must first set a reference to the Standard OLE Types type library in the References dialog box, available by clicking References on the Tools menu. You can then declare an object variable of type Picture.

Note   You can't use the LoadPicture function to set the Picture property of an image control. This function works with custom controls only. To set the Picture property of an image control, simply assign to it a string specifying the filename and path of the desired graphic.


LoadPicture Function Example

The following example uses the LoadPicture function to load a metafile into a custom control on an Employees form. Note that in order to declare a variable of type Picture, you must set a reference to the Standard OLE Types type library in the References dialog, available by clicking References on the Tools menu.

Sub DisplayGraphic()

' Declare object variables of type Picture and Control.

Dim pic As Picture, ctl As Control

' Set Control variable to refer to custom control on form.

Set ctl = Forms!Employees!SomeCustomControl

' Assign return value of LoadPicture to Picture object.

Set pic = LoadPicture("C:\MSOffice\Access\Bitmaps\Styles\Globe.wmf")

' Set Picture property of custom control.

Set ctl.Picture = pic

End Sub


Determining the Error Codes Reserved by Visual Basic

The following procedure creates a table in Microsoft Access containing the error codes and strings used or reserved by Visual Basic. The table does not include data access errors.

Visual Basic reserves a portion of the first 1000 possible error numbers, so this example considers only error numbers between 1 and 1000. Other error numbers are reserved by the Microsoft Jet database engine, or are available for defining custom errors.

Sub CreateErrorsTable()

Dim dbs As Database, tdf As TableDef, fld As Field

Dim rst As Recordset, lngCode As Long

Const conAppObjectError = "Application-defined or object-defined error"

' Create Errors table with ErrorNumber and ErrorDescription fields.

Set dbs = CurrentDb

Set tdf = dbs.CreateTableDef("Errors")

Set fld = tdf.CreateField("ErrorCode", dbLong)

tdf.Fields.Append fld

Set fld = tdf.CreateField("ErrorString", dbText, 255)

tdf.Fields.Append fld

dbs.TableDefs.Append tdf

' Open recordset on Errors table.

Set rst = dbs.OpenRecordset("Errors")

' Loop through first 1000 Visual Basic error codes.

For lngCode = 1 To 1000

On Error Resume Next

' Raise each error.

Err.Raise lngCode

DoCmd.Hourglass True

' Skip error codes generating application or object-defined errors.

If Err.Description <> conAppObjectError Then

' Add each error code and string to Errors table.

rst.AddNew

rst!ErrorCode = Err.Number

rst!ErrorString = Err.Description

rst.Update

End If

' Clear Err object.

Err.Clear

Next lngCode

' Close recordset.

rst.Close

DoCmd.Hourglass False

MsgBox "Errors table created."

End Sub


Converting Code That Calls a DLL

Calling the Windows Application Programming Interface

If a database created in previous versions of Microsoft Access called procedures in the Microsoft Windows Application Programming Interface (API), you will need to make some changes in your code when you convert the database to Microsoft Access 95.

The Windows API consists of a set of dynamic-link libraries (DLLs) containing system-related procedures that include functions, messages, data structures, data types, and statements you can use in creating applications that run under Windows 95. In order to call these procedures from Visual Basic, you must first declare them using a Declare statement. You can then call them as you would any other procedure.

Previous versions of Microsoft Access were 16-bit applications and ran on 16-bit versions of Windows. Microsoft Access 95 is a 32-bit application and runs only on 32-bit versions of Windows [image] Windows 95 and Windows NT. If your existing Access Basic code made calls to a 16-bit Windows API, you will need to modify these calls when you convert your database to Microsoft Access 95. The following list provides some tips for converting your code.

Check any Declare statements to ensure that they refer to the correct DLLs. The following table shows the new names for the 32-bit Windows DLLs.

16-bit Windows DLL	32-bit Windows DLL
User.dll	User32.dll
Kernel.dll	Kernel32.dll
GDI.dll	GDI32.dll
The names of some functions in the 32-bit Windows API have changed. Additionally, functions in the 32-bit Windows API are case-sensitive. Check to make sure that you've entered the procedure name and alias name correctly.

Some functions have new parameter data types in the 32-bit Windows APIs. Consult one of the references listed below to determine which function calls you must update.

If an older version of a DLL exists on your computer, Microsoft Access may try to call a function in that DLL if the directory in which it resides precedes the directory that contains the new version in your path. Check your machine for older versions.

Some 32-bit DLLs contain functions with slightly different versions to accommodate both Unicode and ANSI strings. An A at the end of the function name specifies the ANSI version. A W at the end of the function name specifies the Unicode version. If the function takes string-type arguments, try appending an A to the function name.

For more information on using 32-bit Windows APIs and on porting your existing database applications to 32-bit Microsoft Access, consult the following resources:

The Windows API Viewer, available in the Microsoft Access Developer's Toolkit, includes Visual Basic syntax for all 32-bit declarations, data types, and constants.

The Microsoft Office Resource Kit contains information on porting your 16-bit Microsoft Office-based solutions, including applications developed with previous versions of Microsoft Access, to 32-bit solutions.

The Microsoft Win32 Software Development Kit provides complete reference information on 32-bit Windows APIs.

Calling Code in Other DLLs

If your database application calls procedures in other DLLs, you must create or obtain 32-bit versions of those DLLs and make any necessary modifications to your code when you convert your database to Microsoft Access 95.

If you can't obtain a 32-bit version of a DLL, then you'll need an intermediary DLL that can convert 32-bit calls to 16-bit calls. For more information, see the resources listed above.


Microsoft Access Objects


Using International Date Formats in SQL Statements

You must use U.S./English date formats in SQL statements in Visual Basic. However, you can use international date formats in the query design grid.


Echo Method

The Echo method specifies whether Microsoft Access repaints or updates the computer screen.

Syntax

Application.Echo echoon[, statusbartext]

The Echo method uses the following arguments.

Argument	Description

echoon	True (default) indicates that the screen is repainted; False indicates that the screen isn't repainted.

statusbartext	Optional string expression that specifies the text to display in the status bar when repainting is turned on or off.

Remarks

If you are running Visual Basic code that makes a number of changes to objects displayed on the screen, your code may be faster if you turn off screen repainting until the procedure has finished running. You may also want to turn repainting off if your code makes changes that the user shouldn't see or doesn't need to see.

The Echo method doesn't suppress the display of modal dialog boxes, such as error messages, or pop-up forms, such as property sheets.

If you turn screen repainting off, the screen will not show any changes, even if the user presses CTRL+BREAK or Visual Basic encounters a breakpoint, until you turn screen repainting back on. You may want to create a macro that turns repainting on and assign the macro to a key or custom menu command. You can then use the key combination or menu command to turn repainting on if it has been turned off in Visual Basic.

If you turn screen repainting off and then try to step through your code, you won't be able to see your progress through the code, or any other visual cues, until repainting is turned back on. However, your code will continue to execute.

Note   Don't confuse the Echo method with the Repaint method. The Echo method turns screen updating on or off. The Repaint method forces an immediate screen update.


Echo Method Example

The following example uses the Echo method to prevent the screen from being repainted while certain operations are underway. While the procedure opens a form and minimizes it, the user only sees an hourglass to indicate that processing is taking place, and the screen is not repainted. When this task is completed, the hourglass changes back to a pointer and screen repainting is restored.

Sub EchoOff()

Application.Echo False	' Echo off.

DoCmd.Hourglass True	' Hourglass on.

DoCmd.OpenForm "Employees", acNormal	' Open form.

DoCmd.Minimize	' Minimize form.

Application.Echo True	' Echo on.

DoCmd.Hourglass False	' Hourglass off.

End Sub


GetOption, SetOption Methods

The GetOption method returns the current value of an option in the Options dialog box, available by clicking Options on the Tools menu.

The SetOption method sets the current value of an option in the Options dialog box, available by clicking Options on the Tools menu.

Syntax

Application.GetOption(optionname)

Application.SetOption optionname, setting

The GetOption and SetOption methods use the following arguments.

Argument	Description

optionname	The name of the option.

setting	A Variant value corresponding to the option setting. The value of setting depends on the possible settings for a particular option.

Remarks

The GetOption and SetOption methods provide a means of changing environment options from Visual Basic code. With these methods, you can set or read any option available in the Options dialog box, except for options on the Modules tab.

The option setting depends on the type of option being set. There are three general types of options:

Yes/No options that can be set by selecting or clearing a check box.

Options that can be set by entering a string or numeric value.

Predefined options that can be chosen from a drop-down box or option group.

For options that the user sets by selecting or clearing a check box, the GetOption method returns True if the option setting is Yes (the check box is selected) or False if the option setting is No (the check box is cleared). To set an option of this kind using the SetOption method, specify True or False for the setting argument, as in the following example.

Application.SetOption "Show Status Bar", True

For options that the user sets by typing a string or numeric value, the GetOption method returns the setting as it is displayed in the dialog box. The following example returns a string containing the left margin setting.

Dim varX As Variant

varX = Application.GetOption("Left Margin")

To set this type of option using the SetOption method, specify the string or numeric value that would be typed in the dialog box. The following example sets the default form template to OrderTemplate.

Application.SetOption "Form Template", "OrderTemplate"

For options with settings that are choices in list boxes, the GetOption method returns a number corresponding to the position of the setting in the list. Indexing begins with zero, so the GetOption method returns zero for the first item, 1 for the second item, and so on. For example, if the Default Field Type option on the Tables/Queries tab is set to AutoNumber, the sixth item in the list, the GetOption method returns 5.

To set this type of option, specify the option's numeric position within the list as an argument to the SetOption method. The following example sets the Default Field Type option to AutoNumber.

Application.SetOption "Default Field Type", 5

Other options are set by clicking on an option button in an option group in the Options dialog box. In Visual Basic, these options are also set by specifying a particular option's position within the option group. The first option in the group is numbered zero, the second, 1, and so on. For example, if the Selection Behavior option on the Forms/Reports tab is set to Partially Enclosed, the GetOption method returns zero.

Debug.Print Application.GetOption("Selection Behavior")

To set an option that is a member of an option group, specify the index number of the option within the group. The following example sets Selection Behavior to Fully Enclosed.

Application.SetOption "Selection Behavior", 1

Note   When you use the GetOption method or the SetOption method to set an option in the Options dialog box, you don't need to specify the individual tab on which the option is found.

You can't use the GetOption method or the SetOption method to read or set any of the options found on the Module tab of the Options dialog box.

If the return value of the GetOption method is assigned to a variable, the variable must be declared as a Variant.

When you quit Microsoft Access, you can reset all options to their original settings by using the SetOption method on all changed options. You may want to create public variables to store the values of the original settings. You might include code to reset options in the Close event procedure for a form, or in a custom exit procedure that the user must run to quit the application.

For a complete list of options that can be set from Visual Basic, see Setting Startup Properties and Options in Code.


GetOption, SetOption Methods Example

The following example uses the GetOption method to return the Default Field Type option setting from the Tables/Queries tab of the Options dialog box and then saves the setting in a variable. If the Default Field Type option isn't currently set to Text, Microsoft Access displays a dialog box asking the user whether it should set the option to Text. If the user clicks Yes, the SetOption method changes the option.

Sub ChangeFieldSize()

' Constant represents Text setting of Default Field Type option.

Const conText = 0

Dim varSize As Variant, intResponse As Integer, strMsg As String

' Determine current setting.

varSize = Application.GetOption("Default Field Type")

strMsg = "Set default field type to Text?"

If varSize <> conText Then

' Prompt user to change setting if it's not Text.

If MsgBox(strMsg, vbYesNo) = vbYes Then

' Change setting to Text.

Application.SetOption "Default Field Type", conText

End If

End If

End Sub


GoToPage Method

The GoToPage method moves the focus to the first control on a specified page in the active form.

Syntax

form.GoToPage pagenumber[, right, down]

The GoToPage method uses the following arguments.

Argument	Description

form	A Form object that represents the active form

pagenumber	A numeric expression that is a valid page number for the active form

right	A numeric expression that is a valid horizontal offset (in twips) from the left side of the window to the part of the page to be viewed

down	A numeric expression that is a valid vertical offset (in twips) for from the top of the window to the part of the page to be viewed

Remarks

When you use this method to move to a specified page of a form, the focus is set to the first control on the page, as defined by the form's tab order. To move to a particular control on the form, use the SetFocus method.

You can use the GoToPage method if you have created page breaks on a form to group related information. For example, you might have an Employees form with personal information on the first page, office information on the second page, and sales information on the third page. You can use the GoToPage method to move to the desired page.

You can use the right and down arguments for forms with pages larger than the Microsoft Access application window. Use the pagenumber argument to move to the desired page, and then use the right and down arguments to display the part of the page you want to see. Microsoft Access displays the part of the page which is offset from the upper-left corner of the window by the distance specified in the right and down arguments.


GoToPage Method Example

The following example uses the GoToPage method to move the focus to the second page of the Customer form at the position specified by the right and down arguments.

Forms!Customer.GoToPage 2, 1440, 600


ItemData Method

The ItemData method returns the data in the bound column for the specified row in a list box or combo box.

Syntax

control.ItemData(rowindex)

The ItemData method uses the following arguments.

Argument	Description

control	A Control object that represents a combo box or list box.

rowindex 	The row in the combo box or list box containing the data you want to return. Rows in combo and list boxes are indexed starting with zero. For example, to return the item in the sixth row of a combo box, you'd specify 5 for rowindex.

Remarks

The ItemData method enables you to iterate through the list of entries in a combo box or list box. For example, suppose you wanted to iterate through all of the items in a list box to search for a particular entry. You can use the ListCount property to determine the number of rows in the list box, and then use the ItemData method to return the data for the bound column in each row.

You can also use the ItemData method to return data only from selected rows in a list box. You can iterate through the ItemsSelected collection to determine which row or rows in the list box have been selected, and use the ItemData method to return the data in those rows. You must set the MultiSelect property of the list box to Simple or Extended to enable the user to select more than one row at a time.

Tip   You can use the Column property to return data from a specified row and column, even if the specified column is not the bound column.


ItemData Method Example

The following example prints the value of the bound column for each selected row in a list box EmployeeList on an Employees form.

Sub RowsSelected()

Dim ctlList As Control, varItem As Variant

' Return Control object variable pointing to list box.

Set ctlList = Forms!Employees!EmployeeList

' Set MultiSelect property to Simple.

ctlList.MultiSelect = 2

' Enumerate through selected items.

For Each varItem in ctlList.ItemsSelected

' Print value of bound column.

Debug.Print ctlList.ItemData(varItem)

Next varItem

End Sub


Quit Method

Use the Quit method to quit Microsoft Access. You can select one of several options for saving a database object before quitting.

Syntax

Application.Quit [option]

The Quit method uses the following argument.

Argument	Description

option	An intrinsic constant that specifies what happens to unsaved objects when you quit Microsoft Access. It can be any of the following constants:

(Default) acSaveYes saves all objects without displaying a dialog box.

acPrompt displays a dialog box that asks whether you want to save any database objects that have been changed but not saved.

acExit quits Microsoft Access without saving any objects.

Remarks

The Quit method has the same effect as clicking Exit on the File menu. You can create a custom menu command or a button on a form with a procedure that includes the Quit method. For example, you can place a Quit button on a form and include a procedure in the button's Click event that uses the Quit method with option set to acSaveYes.


Quit Method Example

The following example shows the Click event procedure for a command button named AppExit. After clicking the AppExit button, a dialog box prompts the user to save changes, and the procedure quits Microsoft Access.

Private Sub AppExit_Click()

Application.Quit acPrompt

End Sub


Refresh Method

The Refresh method immediately updates the records in the underlying record source for a specified form or datasheet to reflect changes made to the data by you and other users in a multiuser environment.

Syntax

form.Refresh

The Refresh method uses the following argument.

Argument	Description

form	A Form object that represents the form to refresh

Remarks

Using this method is equivalent to clicking Refresh on the Records menu.

Microsoft Access refreshes records automatically, based on the Refresh Interval setting on the Advanced tab of the Options dialog box, available by clicking Options on the Tools menu. ODBC data sources are refreshed based on the ODBC Refresh Interval setting on the Advanced tab of the Options dialog box. You can use the Refresh method to view changes that have been made to the current set of records in a form or datasheet since the record source underlying the form or datasheet was last refreshed.

The Refresh method shows only changes made to records in the current set. Since the Refresh method doesn't actually requery the database, the current set will not include records that have been added or exclude records that have been deleted since the database was last requeried. Nor will it exclude records that no longer satisfy the criteria of the query or filter. To requery the database, use the Requery method. When the record source for a form is requeried, the current set of records will accurately reflect all data in the record source.

Note   It's often faster to refresh a form or datasheet than to requery it. This is especially true if the initial query was slow to run.

Don't confuse the Refresh method with the Repaint method, which updates the screen with any pending visual changes.


Refresh Method Example

The following example uses the Refresh method to update the records in the underlying record source for the form Customers whenever the form receives the focus.

Private Sub Form_Activate()

Forms!Customers.Refresh

End Sub


Repaint Method

The Repaint method completes any pending screen updates for a specified form. When performed on a form, the Repaint method also completes any pending recalculations of the form's controls.

Syntax

form.Repaint

The Repaint method uses the following argument.

Argument	Description

form	A Form object that represents the form to repaint

Remarks

Microsoft Access sometimes waits to complete pending screen updates until it finishes other tasks. With the Repaint method, you can force immediate repainting of the controls on the specified form. You can use the Repaint method:

When you change values in a number of fields. Unless you force a repaint, Microsoft Access might not display the changes immediately, especially if other fields, such as those in an expression in a calculated control, depend on values in the changed fields.

When you want to make sure that a form displays data in all of its fields. For example, fields containing OLE objects often don't display their data immediately after you open a form.

This method doesn't cause a requery of the database, nor does it show new or changed records in the form's underlying record source. You can use the Requery method to requery the source of data for the form or one of its controls.

Note   Don't confuse the Repaint method with the Refresh method, or with the Refresh command on the Records menu. The Refresh method and Refresh command show changes you or other users have made to the underlying record source for any of the currently displayed records in forms and datasheets. The Repaint method simply updates the screen when repainting has been delayed while Microsoft Access completes other tasks.

The Repaint method differs from the Echo method in that the Repaint method forces a single immediate screen update, while the Echo method turns screen updating on or off.


Repaint Method Example

The following example uses the Repaint method to repaint a Customer form when the form receives the focus.

Private Sub Form_Activate()

Forms!Customers.Repaint

End Sub


Requery Method

The Requery method updates the data underlying a specified form, or a control that is on the active form, by requerying the source of data for the form or control.

Syntax

object.Requery

The Requery method uses the following argument.

Argument	Description

object	A Form or Control object representing the form or control you want to update. Omit this argument to requery the source of data for the active object.

Remarks

Use this method to ensure that a form or control displays the most recent data.

The Requery method does one of the following:

Reruns the query on which the form or control is based.

Displays any new or changed records or removes deleted records from the table on which the form or control is based.

Updates records displayed based on any changes to the Filter property of the form.

Controls based on a query or table include:

List boxes and combo boxes

Subform controls

OLE objects, such as charts

Controls for which the ControlSource property setting includes domain aggregate functions or SQL aggregate function

If you specify any other type of control for object, the record source for the form is requeried.

If the control specified by object isn't bound to a field in a table or query, the Requery method forces a recalculation of the control.

If you omit object, the Requery method requeries the underlying source of data for the form or control that has the focus. If the control that has the focus has a record source or row source, it will be requeried; otherwise the control's data will simply be refreshed.

If a subform control has the focus, this method only requeries the record source for the subform, not the parent form.

Note   The Requery method updates the data underlying a form or control to reflect records that are new to or have been deleted from the record source since it was last requeried. The Refresh method shows only changes that have been made to the current set of records; it does not reflect new records or deleted records in the record source. The Repaint method simply repaints the specified form and its controls.

The Requery method doesn't pass control to the operating system to allow Windows to continue processing messages. Use the DoEvents function if you need to relinquish temporary control to the operating system.

The Requery method is faster than the Requery action. When you use the Requery action, Microsoft Access closes the query and reloads it from the database. When you use the Requery method, Microsoft Access reruns the query without closing and reloading it.


Requery Method Example

This example uses the Requery method to requery the data from the EmployeeList list box on an Employees form.

Sub RequeryList()

Dim ctlList As Control

' Return Control object pointing to list box.

Set ctlList = Forms!Employees!EmployeeList

' Requery source of data for list box.

ctlList.Requery

End Sub


SetFocus Method

The SetFocus method moves the focus to the specified form, the specified control on the active form, or the specified field on the active datasheet.

Syntax

object.SetFocus

The SetFocus method uses the following argument.

Argument	Description

object	A Form object that represents a form, or a Control object that represents a control on the active form or datasheet

Remarks

Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object.

In order to read some of the properties of a control, you need to ensure that that control has the focus. For example, a text box must have the focus before you can read its Text property.

Other properties can be set only when a control doesn't have the focus. For example, you can't set a control's Visible or Locked properties to False when that control has the focus.

You can also use the SetFocus method to navigate in a form according to certain conditions. For example, if the user selects Not Applicable for the first of a set of questions on a form that is a questionnaire, your Visual Basic code might then automatically skip the questions in that set and move the focus to the first control in the next set of questions.

You can move the focus only to a visible control or form. A form and controls on a form aren't visible until the form's Load event has finished. Therefore, if you use the SetFocus method in a form's Load event to move the focus to that form, you must use the Repaint method before the SetFocus method.

You can't move the focus to a control if its Enabled property is set to False. You must set a control's Enabled property to True before you can move the focus to that control. You can, however, move the focus to a control if its Locked property is set to True.

If a form contains controls for which the Enabled property is set to True, you can't move the focus to the form itself. You can only move the focus to controls on the form. In this case, if you try to use SetFocus to move the focus to a form, the focus is set to the control on the form that last received the focus.

Tip   You can use the SetFocus method to move the focus to a subform, which is a type of control. You can also move the focus to a control on a subform by using the SetFocus method twice, moving the focus first to the subform and then to the control on the subform.


SetFocus Method Example

The following example uses the SetFocus method to move the focus to an EmployeeID text box on an Employees form.

Dim ctlText As Control

Set ctlText = Forms!Employees!EmployeeID

ctlText.SetFocus


Circle Method

The Circle method draws a circle, an ellipse, or an arc on a Report object when the Print event occurs.

Syntax

object.Circle [Step](x, y), radius[, [color][, [start][, [end][, aspect]]]]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The Circle method uses the following arguments.

Argument	Description

object	Report object on which the circle is drawn.

Step	A key word that specifies that the center of the circle, ellipse, or arc is relative to the current coordinates given by the current settings for the CurrentX and CurrentY properties of object.

x, y	Single values indicating the coordinates of the center point of the circle, ellipse, or arc. The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used.

radius	A Single value indicating the radius of the circle, ellipse, or arc. The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used. By default distances are measured in twips.

color	A Long value indicating the RGB (red-green-blue) color of the circle outline. If this argument is omitted, the value of the ForeColor property is used. You can also use the RGB function or QBColor function to specify the color.

start, end	Single values. When a partial circle or ellipse is drawn, start and end specify (in radians) the beginning and end positions of the arc. The default value for start is 0 radians; the default for end is 2 pi radians. The range for both is -2 pi radians to 2 pi radians.

aspect	Single value indicating the aspect ratio of the circle. The default value is 1.0, which yields a perfect (nonelliptical) circle on any screen.

Remarks

When drawing a partial circle or ellipse, if start is negative, the Circle method draws a radius to start and treats the angle as positive. If end is negative, the Circle method draws a radius to end and again treats the angle as positive. The Circle method always draws in a counterclockwise (positive) direction.

To fill a circle, set the FillColor and FillStyle properties of the report. Only a closed figure can be filled. Closed figures include circles, ellipses, and pie slices, which are arcs with radius lines drawn at both ends.

When drawing pie slices, if you need to draw a radius to angle 0 to form a horizontal line segment to the right, specify a very small negative value for start rather than 0. For example, you might specify -.00000001 for start.

You can omit an argument in the middle of the syntax, but you must include the argument's comma before including the next argument. If you omit a trailing argument, don't use any commas following the last argument you specify.

The width of the line used to draw the circle, ellipse, or arc depends on the DrawWidth property setting. The way the circle is drawn on the background depends on the settings of the DrawMode and DrawStyle properties.

When you apply the Circle method, the CurrentX and CurrentY properties are set to the center point specified by the arguments x and y.


Circle Method Example

The following example uses the Circle method to draw a circle, and then create a pie slice within the circle and color it red.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report's module, then switch to Print Preview.

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer)

Const conPI = 3.14159265359

Dim sngHCtr As Single, sngVCtr As Single, sngRadius As Single

Dim sngStart As Single, sngEnd As Single

sngHCtr = Me.ScaleWidth / 2	' Horizontal center.

sngVCtr = Me.ScaleHeight / 2	' Vertical center.

sngRadius = Me.ScaleHeight / 3	' Circle radius.

Me.Circle(sngHCtr, sngVCtr), sngRadius	' Draw circle.

sngStart = -0.00000001	' Start of pie slice.

sngEnd = -2 * conPI / 3	' End of pie slice.

Me.FillColor = RGB(255,0,0)	' Color pie slice red.

Me.FillStyle = 0	' Fill pie slice.

' Draw Pie slice within circle

Me.Circle(sngHCtr, sngVCtr), sngRadius, , sngStart, sngEnd

End Sub


Line Method

The Line method draws lines and rectangles on a Report object when the Print event occurs.

Syntax

object.Line [[Step](x1, y1)] - [Step](x2, y2)[, [color][, B[F]]]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The Line method uses the following arguments.

Argument	Description

object	The Report object on which the line or rectangle is to be drawn.

Step	A key word that indicates the starting point coordinates are relative to the current graphics position given by the settings for the CurrentX and CurrentY properties of object.

x1, y1	Single values indicating the coordinates of the starting point for the line or rectangle. The Scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used. If this argument is omitted, the line begins at the position indicated by the CurrentX and CurrentY properties.

Step	A key word that indicates the end-point coordinates are relative to the line's starting point.

x2, y2	Single values indicating the coordinates of the end point for the line to draw. These coordinates are required.

color	A Long value indicating the RGB (red-green-blue) color used to draw the line. If this argument is omitted, the ForeColor property is used. You can also use the RGB function or QBColor function to specify the color.

B	An option that creates a rectangle using the coordinates as opposite corners of the rectangle.

F	F cannot be used without B. If the B option is used, the F option specifies that the rectangle is filled with the same color used to draw the rectangle. If B is used without F, the rectangle is filled with the color specified by the current settings of the FillColor and BackStyle properties. The default value for the BackStyle property is Normal for rectangles and lines.

Remarks

To connect two drawing lines, make sure that one line begins at the end point of the previous line.

The width of the line drawn depends on the DrawWidth property setting. The way a line or rectangle is drawn on the background depends on the settings of the DrawMode and DrawStyle properties.

When you apply the Line method, the CurrentX and CurrentY properties are set to the end point specified by the x2 and y2 arguments.


Line Method Example

The following example uses the Line method to draw a red rectangle five pixels inside the edge of a report named EmployeeReport. The RGB function is used to make the line red.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report's module, then switch to Print Preview.

Sub DrawLine()

Dim rpt As Report, intColor As Integer

Dim sngTop As Single, sngLeft As Single

Dim sngWidth As Single, sngHeight As Single

Set rpt = Reports!EmployeeReport

rpt.ScaleMode = 3	' Set scale to pixels.

sngTop = rpt.ScaleTop + 5	' Top inside edge.

sngLeft = rpt.ScaleLeft + 5	' Left inside edge.

sngWidth = rpt.ScaleWidth - 10	' Width inside edge.

sngHeight = rpt.ScaleHeight - 10	' Height inside edge.

intColor = RGB(255,0,0)	' Make color red.

' Draw line as a box.

rpt.Line(sngTop, sngLeft) - (sngWidth, sngHeight), intColor, B

End Sub


PSet Method

The PSet method sets a point on a Report object to a specified color when the Print event occurs.

Syntax

object.PSet [Step](x, y)[, color]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The PSet method uses the following arguments.

Argument	Description

object	The Report object on which the point is to be drawn.

Step	A key word that indicates the coordinates are relative to the current graphics position given by the settings for the CurrentX and CurrentY properties of object.

x, y	Single values indicating the horizontal and vertical coordinates of the point to set.

color	An RGB (red-green-blue) color to set the point to. If this argument is omitted, the current foreground color is used. You can also use the RGB function or the QBColor function to specify the color.

Remarks

The size of the point depends on the DrawWidth property setting. When the DrawWidth property is set to 1, the PSet method sets a single pixel to the specified color. When the DrawWidth property is greater than 1, the point is centered on the specified coordinates.

The way the point is drawn depends on the settings of the DrawMode and DrawStyle properties.

When you apply the PSet method, the CurrentX and CurrentY properties are set to the point specified by the x and y arguments.

To clear a single pixel with the PSet method, specify the coordinates of the pixel and use white (&HFFFFFF) as the color argument.


PSet Method Example

The following example uses the PSet method to draw a line through the horizontal axis of a report.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report's module, then switch to Print Preview.

Sub Detail_Print(Cancel As Integer, PrintCount As Integer)

Dim sngMidPt As Single, intI As Integer

rpt.ScaleMode = 3	' Set scale to pixels.

sngMidPt = rpt.ScaleHeight / 2	' Calculate midpoint.

' Loop to draw line down horizontal axis pixel by pixel.

For intI = 1 To rpt.ScaleWidth

rpt.PSet(intI, sngMidPt)

Next intI

End Sub

Tip   It's faster to draw a line using the Line method rather than the PSet method.


Scale Method

The Scale method defines the coordinate system for a Report object.

Syntax

object.Scale[(x1, y1) - (x2, y2)]

You can use this method only in an event procedure or a macro specified by the event properties OnPrint or OnFormat for a report section, or OnPage for a report.

The Scale method uses the following arguments.

Argument	Description

object	The Report object to which the coordinate system is applied

x1, y1	Single values for the horizontal and vertical coordinates that define the position of the upper-left corner of the object

x2, y2	Single values for the horizontal and vertical coordinates that define the position of the lower-right corner of the object

Remarks

You can use the Scale method to reset the coordinate system to any scale you choose. Using the Scale method with no arguments resets the coordinate system to twips. The Scale method affects the coordinate system for the Print method and the report graphics methods, which include the Circle, Line, and PSet methods.


TextHeight Method

The TextHeight method returns the height of a text string as it would be printed in the current font of a Report object.

Syntax

object.TextHeight(strexpr)

The TextHeight method uses these arguments.

Argument	Description

object	The Report object that determines the font and point size

strexpr	The text string for which the text height will be determined

Remarks

You can use the TextHeight method to determine the amount of vertical space a text string will require in the current font when the report is formatted and printed. For example, a text string formatted in nine-point Arial will require a different amount of space than one formatted in twelve-point Courier. To determine the current font and point size for text in a report, check the settings for the report's FontName and FontSize properties.

The value returned by the TextHeight method is expressed in terms of the coordinate system in effect for the report, as defined by the Scale method. You can use the ScaleMode property to determine the coordinate system currently in effect for the report.

If strexpr contains embedded carriage returns, the TextHeight method returns the cumulative height of the lines, including the leading space above and below each line. You can use the value returned by the TextHeight method to calculate the necessary space and positioning for multiple lines of text within a report.


TextHeight, TextWidth Methods Example

The following example uses the TextHeight and TextWidth methods to determine the amount of vertical and horizontal space required to print a text string in the report's current font.

To try this example in Microsoft Access, create a new report by clicking the New button on the Reports tab of the Database window. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report's module, then switch to Print Preview.

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer)

' Set unit of measure to twips (default scale).

Me.Scalemode = 1

' Print name and point size of report font.

Debug.Print "Report Font: "; Me.FontName

Debug.Print "Report Font Size: "; Me.FontSize

' Print height and width required for text string.

Debug.Print "Text Height (Twips): "; Me.TextHeight("Product Report")

Debug.Print "Text Width (Twips): "; Me.TextWidth("Product Report")

End Sub


TextWidth Method

The TextWidth method returns the width of a text string as it would be printed in the current font of a Report object.

Syntax

object.TextWidth(strexpr)

The TextWidth method uses the following arguments.

Argument	Description

object	The Report object that determines the font and point size

strexpr	The text string for which the text width will be determined

Remarks

You can use the TextWidth method to determine the amount of horizontal space a text string will require in the current font when the report is formatted and printed. For example, a text string formatted in nine-point Arial will require a different amount of space than one formatted in 12-point Courier. To determine the current font and point size for text in a report, check the settings for the report's FontName and FontSize properties.

The value returned by the TextWidth method is expressed in terms of the coordinate system in effect for the report, as defined by the Scale method. You can use the ScaleMode property to determine the coordinate system currently in effect for the report.

If strexpr contains embedded carriage returns, the TextWidth method returns the width of the longest line, from the beginning of the line to the carriage return. You can use the value returned by the TextWidth method to calculate the necessary space and positioning for multiple lines of text within a report.


Recalc Method

The Recalc method immediately updates all calculated controls on a form.

Syntax

form.Recalc

The Recalc method uses the following argument.

Argument	Description

form	A Form object representing the form that contains the controls for which you want to recalculate the values.

Remarks

Using this method is equivalent to pressing the F9 key when a form has the focus. You can use this method to recalculate the values of controls that depend on other fields for which the contents may have changed.


Recalc Method Example

The following example uses the Recalc method to update controls on an Orders form. This form includes the Freight text box, which displays the freight cost, and a calculated control that displays the total cost of an order including freight. If the statement containing the Recalc method is placed in the AfterUpdate event procedure for the Freight text box, the total cost of an order is recalculated every time a new freight amount is entered.

Sub Freight_AfterUpdate()

Forms!Orders.Recalc

End Sub


DoCmd Object

You can use the methods of the DoCmd object to run Microsoft Access actions from Visual Basic. An action performs tasks such as closing windows, opening forms, and setting the value of controls. For example, you can use the OpenForm method of the DoCmd object to open a form, or use the Hourglass method to change the mouse pointer to an hourglass icon.

Syntax

[application.]DoCmd.method [arg1, arg2, ...]

The DoCmd object uses the following arguments.

Argument	Description

application	Optional. The Application object.

method	One of the methods supported by this object.

arg1, arg2, ...	The arguments for the selected method. These arguments are the same as the action arguments for the corresponding action.

Remarks

Most of the methods of the DoCmd object have arguments [image] some are required, while others are optional. If you omit optional arguments, the arguments assume the default values for the particular action. For example, the OpenForm method uses seven arguments, but only the first argument, formname, is required. The following example shows how you can open the Employees form in the current database. Only employees with the title Sales Representative are included.

DoCmd.OpenForm "Employees", , ,"[Title] = 'Sales Representative'"

The DoCmd object does not support methods corresponding to the following actions:

AddMenu

MsgBox [image] Use the MsgBox function.

RunApp [image] Use the Shell function to run another application.

RunCode [image] Run the function directly in Visual Basic.

SendKeys [image] Use the SendKeys statement.

SetValue [image] Set the value directly in Visual Basic.

StopAllMacros

StopMacro

For more information on the Microsoft Access action corresponding to a DoCmd method, search the online index for the name of the action or ask the Answer Wizard.


DoCmd Object Example

The following example opens a form in Form view and moves to a new record.

Sub NewRecord()

DoCmd.OpenForm "Employees", acNormal	' Open form.

DoCmd.GoToRecord , , acNewRec	' Move to new record.

End Sub


OpenCurrentDatabase Method

You can use the OpenCurrentDatabase method to open an existing database as the current database. You can use the this method to open a database from another application that is controlling Microsoft Access through OLE Automation. For example, you can use the OpenCurrentDatabase method from Microsoft Excel to open the Northwind sample database in the Microsoft Access window.

Syntax

application.OpenCurrentDatabase dbname[, exclusive]

The OpenCurrentDatabase method uses the following arguments.

Argument	Description

application	The Application object.

dbname	A string expression that is the name of an existing database file, including the path name and the filename extension. If your network supports it, you can also specify a network path in the following form.
\\Server\Share\Directory\Filename.mdb

exclusive	Optional. An Integer value that specifies whether you want to open the database in exclusive mode. By default the database opens in shared mode.

Remarks

The OpenCurrentDatabase method enables you to open a Microsoft Access database from another application through OLE Automation. Once you have created an instance of Microsoft Access from another application, you must also create a new database or specify a particular database to open. This database opens in the Microsoft Access window.

If you have already opened a database and wish to open another database in the Microsoft Access window, you can use the CloseCurrentDatabase method to close the first database before opening another.

Set the exclusive argument to True (-1) to open the database in exclusive mode. If you omit this argument, the database will open in the shared mode.

If the database identified by dbname does not exist, an error occurs.

Note   Don't confuse the OpenCurrentDatabase method with the data access OpenDatabase method. The OpenCurrentDatabase method opens a database in the Microsoft Access window. The OpenDatabase method returns a Database object variable that represents a particular database, but doesn't actually open that database in the Microsoft Access window.


OpenCurrentDatabase Method Example

The following example opens a Microsoft Access database from another application through OLE Automation, then opens a form in that database.

You can enter this code in a Visual Basic module in any application that can act as an OLE Automation controller. For example, you might run the following code from Microsoft Excel, Microsoft Visual Basic, or even Microsoft Access.

When the variable pointing to the Application object goes out of scope, the instance of Microsoft Access that it represents closes as well. Therefore, you should declare this variable at the module level.

' Include following in Declarations section of module.

' From Microsoft Excel, use "Dim appAccess As Object".

Dim appAccess As Access.Application

Sub DisplayForm()

Dim strDB As String

' Initialize string to database path.

strDB = "C:\Office95\Access\Samples\Northwind.mdb"

' Create new instance of Microsoft Access.

Set appAccess = CreateObject("Access.Application.7")

' Open database in Microsoft Access window.

appAccess.OpenCurrentDatabase strDB

' Open Orders form.

appAccess.DoCmd.OpenForm "Orders"

End Sub

Note   From some applications, such as Microsoft Visual Basic 4.0, you can include the New keyword when declaring the Application object variable. This keyword automatically creates a new instance of Microsoft Access, without requiring you to use the CreateObject function. Check your application's documentation to determine whether it supports this syntax.


NewCurrentDatabase Method

You can use the NewCurrentDatabase method to create a new database in the Microsoft Access window. You can use the this method to create a new database from another application that is controlling Microsoft Access through OLE Automation. For example, you can use the NewCurrentDatabase method from Microsoft Excel to create a new database in the Microsoft Access window.

Syntax

application.NewCurrentDatabase dbname

The NewCurrentDatabase method uses the following arguments.

Argument	Description

application	The Application object.

dbname	A string expression that is the name of a new database file, including the path name and the filename extension. If your network supports it, you can also specify a network path in the following form.
\\Server\Share\Directory\Filename.mdb

Remarks

The NewCurrentDatabase method enables you to create a new Microsoft Access database from another application through OLE Automation. Once you have created an instance of Microsoft Access from another application, you must also create a new database or specify a particular database to open. This database opens in the Microsoft Access window.

If the database identified by dbname already exists, an error occurs.

The new database is opened under the Admin user account.


NewCurrentDatabase Method Example

The following example creates a new Microsoft Access database from another application through OLE Automation, then creates a new table in that database.

You can enter this code in a Visual Basic module in any application that can act as an OLE Automation controller. For example, you might run the following code from Microsoft Excel or Microsoft Visual Basic, or even Microsoft Access.

When the variable pointing to the Application object goes out of scope, the instance of Microsoft Access that it represents closes as well. Therefore, you should declare this variable at the module level.

' Include following in Declarations section of module.

' From Microsoft Excel, use "Dim appAccess As Object".

Dim appAccess As Access.Application

Sub NewAccessDatabase()

Dim dbs As Database, tdf As TableDef, fld As Field

Dim strDB As String

' Initialize string to database path.

strDB = "C:\My Documents\Newdb.mdb"

' Create new instance of Microsoft Access.

Set appAccess = CreateObject("Access.Application.7")

' Open database in Microsoft Access window.

appAccess.NewCurrentDatabase(strDB)

' Get Database variable.

Set dbs = appAccess.CurrentDb

' Create new table.

Set tdf = dbs.CreateTableDef("Contacts")

' Create field in new table.

Set fld = tdf.CreateField("Name", dbText, 20)

' Append Field and TableDef objects.

tdf.Fields.Append fld

dbs.TableDefs.Append tdf

End Sub

Note   From some applications, such as Microsoft Visual Basic 4.0, you can include the New keyword when declaring the Application object variable. This keyword automatically creates a new instance of Microsoft Access, without requiring you to use the CreateObject function. Check your application's documentation to determine whether it supports this syntax.


Run Method

You can use the Run method to carry out a specified Microsoft Access or user-defined Function or Sub procedure. This method is useful when you are controlling Microsoft Access from another application through OLE Automation. For example, you can use the Run method from an OLE Automation controller to carry out a Sub procedure that is defined within a Microsoft Access database.

Syntax

application.Run procedure[, arg1, arg2, ..., arg30]

The Run method uses the following arguments.

Argument	Description

application	The Application object.

procedure	The name of the Function or Sub procedure to be run.

arg1, arg2, ...	Optional. The arguments for the specified Function or Sub procedure. You can supply a maximum of thirty arguments.

Remarks

You can set a reference to the Microsoft Access type library from any other OLE Automation controller and use the objects, methods, and properties defined in that library in your code. However, you can't set a reference to an individual Microsoft Access database from any application other than Microsoft Access. The Run method provides a way to call a procedure you have defined in a Microsoft Access database from another application.

For example, suppose you have defined a procedure NewForm in a database named WizCode.mdb. The NewForm procedure takes a string argument. You can call NewForm in the following manner from Visual Basic 4.0.

Dim appAccess As New Access.Application

appAccess.OpenCurrentDatabase ("C:\My Documents\WizCode.mdb")

appAccess.Run "WizCode.NewForm", "Some String"

If another procedure with the same name may reside in a different database, qualify procedure with the name of the database in which the desired procedure resides.

You can also use the Run method to call a procedure in a referenced Microsoft Access database from another database. Although you can call a procedure in a referenced database as though it were in the current database, doing so loads the potential call tree of the module in the referenced database. For performance and resource reasons, you may want to use the Run method, which loads only the module in which the procedure resides.

Microsoft Access ignores any value returned by a procedure called by the Run method.


Run Method Example

The following example runs a user-defined Sub procedure in a module in a Microsoft Access database from another application that acts as an OLE Automation controller.

To try this example, create a new database called WizCode.mdb and open a new module in that database. Enter the following code, save the module, and close the database.

Sub Greeting(strName As String)

MsgBox("Hello, " & strName)

End Sub

Once you have completed this step, run the following code from Microsoft Excel or Microsoft Visual Basic. Make sure that you have added a reference to the Microsoft Access type library by clicking References on the Tools menu and selecting Microsoft Access For Windows 95 in the References dialog box.

' Include in Declarations section of module.

' From Microsoft Excel, use "Dim appAccess As Object".

Dim appAccess As Access.Application

Sub RunAccessSub()

' Create instance of Microsoft Access Application object.

Set appAccess = CreateObject("Access.Application.7")

' Open WizCode database in Microsoft Access window.

appAccess.OpenCurrentDatabase ("C:\My Documents\WizCode.mdb")

' Run Sub procedure.

appAccess.Run "Greeting", "Joe"

End Sub


Dropdown Method

You can use the Dropdown method to force the list in the specified combo box to drop down. For example, you can use this method to cause a combo box listing vendor codes to drop down when the vendor code field receives the focus during data entry.

Syntax

combobox.Dropdown

The Dropdown method uses the following argument.

Argument	Description

combobox	A combo box control on a form.

Remarks

If the specified combo box control does not have the focus, an error occurs. Using this method is identical to pressing the F4 key when the control has the focus.


Dropdown Method Example

The following example shows how you can use the Dropdown method within the GotFocus event procedure to force a combo box named Employees to drop down when it receives the focus.

Private Sub Employees_GotFocus()

Me!Employees.Dropdown

End Sub


Undo Method

You can use the Undo method to reset a control or form when its value has been changed. For example, you can use the Undo method to clear a change to a record that contains an invalid entry.

Syntax

object.Undo

The Undo method uses the following argument.

Argument	Description

object	A Form object or a Control object.

Remarks

If the Undo method is applied to a form, all changes to the current record are lost. If the Undo method is applied to a control, only the control itself is affected.

This method must be applied before the form or control is updated. You may want to include this method in a form's BeforeUpdate event or a control's Change event.

The Undo method offers an alternative to using the SendKeys statement to send the value of the ESC key in an event procedure.


Undo Method Example

The following example shows how you can use the Undo method within the Change event procedure to force a field named LastName to reset to the original value, if changed.

Private Sub LastName_Change()

Me!LastName.Undo

End Sub

The next example uses the Undo method to reset all changes to a form before the form is updated.

Private Sub Form_BeforeUpdate(Cancel As Integer)

Me.Undo

End Sub


ItemsSelected Collection

The ItemsSelected collection provides a way to access data in the selected rows of a list box or combo box.

Remarks

The ItemsSelected collection is unlike other collections in that it is a collection of Variants rather than of objects. Each Variant is an integer index referring to a selected row in a list box or combo box.

Use the ItemsSelected collection in conjunction with the Column property or the ItemData method to retrieve data from selected rows in a list box or combo box. You can enumerate the ItemsSelected collection using the For Each...Next statement.

For example, if you have an Employees list box on a form, you can enumerate the ItemsSelected collection and use the control's ItemData method to return the value of the bound column for each selected row in the list box.

Tip   To enable multiple selection of rows in a list box or combo box, set the control's MultiSelect property to Simple or Extended.

The ItemsSelected collection has no methods and one property, the Count property.


ItemsSelected Collection Example

The following example prints the value of the bound column for each selected row in a Names list box on a Contacts form. To try this example, create the list box and set its BoundColumn property as desired and its MultiSelect property to Simple or Extended. Switch to Form view, select several rows in the list box, and run the following code.

Sub BoundData()

Dim frm As Form, ctl As Control

Dim varItm As Variant

Set frm = Forms!Contacts

Set ctl = frm!Names

For Each varItm In ctl.ItemsSelected

Debug.Print ctl.ItemData(varItm)

Next varItm

End Sub

The next example uses the same list box control, but prints the values of each column for each selected row in the list box, instead of only the values in the bound column.

Sub AllSelectedData()

Dim frm As Form, ctl As Control

Dim varItm As Variant, intI As Integer

Set frm = Forms!Contacts

Set ctl = frm!Names

For Each varItm In ctl.ItemsSelected

For intI = 0 To ctl.ColumnCount - 1

Debug.Print ctl.Column(intI, varItm)

Next intI

Debug.Print

Next varItm

End Sub


hWndAccessApp Property

You can use the hWndAccessApp property in Visual Basic to determine the handle (a unique Long Integer) assigned by Microsoft Windows 95 to the main Microsoft Access window.

Setting

The hWndAccessApp property is set by Microsoft Access and is read-only.

Remarks

You can use this property in Visual Basic when making calls to Windows 95 Application Programming Interface (API) functions or other external procedures that require a window handle as an argument.

To get the handle to a window containing a Microsoft Access object such as a Form or Report, use the hWnd property.


PictureType Property

You can use the PictureType property to specify whether Microsoft Access stores an object's picture as a linked object or an embedded object.

Setting

The PictureType property uses the following settings.

Setting	Description	Visual Basic

Embedded	(Default) The picture is embedded in the 	0
object and becomes part of the database file.

Linked	The picture is linked to the object. Microsoft 	1
Access stores a pointer to the location of the
picture on the disk.

You can set the PictureType property in the object's property sheet, a macro, or using Visual Basic.

This property can be set only in form or report Design view.

For controls, you can also set this property using the default control style.

Remarks

When the PictureType property is set to Embedded, the size of the database increases by the size of the picture file and, with some .wmf files, the size may increase as much as twice the size of the picture file. When the PictureType property is set to Linked, there is no increase in the size of the database because Microsoft Access only saves a pointer to the picture's location on the disk.

Note    If a linked file is moved to another location on the disk, you must re-establish the link using the object's Picture property.

The individual bits that make up a picture's image are stored in the object's PictureData property.

You can modify a linked picture using a separate application and changes to the picture will appear the next time the object containing that picture is displayed in the database.


BackColor Property

You can use the BackColor property to specify the color for the interior of a control or section.

Setting

The BackColor property contains a numeric expression that corresponds to the color used to fill a control or section's interior.

You can set the BackColor property using the Formatting toolbar, a control's property sheet, a macro, or Visual Basic.

You can also use the Color Builder to set this property by clicking the Build button to the right of the property in the property sheet. Using the Color Builder enables you to define custom back colors for controls.

In Visual Basic, use a numeric expression to set this property. This property setting has a data type of Long.

For controls, you can set the default for this property using a control's default control style.

Remarks

To use the BackColor property, the BackStyle property, if available, must be set to Normal.


BackStyle Property

You can use the BackStyle property to specify whether the control will be transparent.

Setting

The BackStyle property uses the following settings.

Setting	Description	Visual Basic
Normal	(Default for all controls except option group) The control has its interior color set by the BackColor property.	1
Transparent	(Default for option group) The control is transparent. The color of the form or report behind the control is visible.	0
You can set this property using the Formatting toolbar, a control's property sheet, a macro, or Visual Basic.

You can set the default for this property using a control's default control style.

Remarks

If the Transparent button on the BackColor toolbar palette is selected, the BackStyle property is set to Transparent; otherwise the BackStyle property is set to Normal.

Tip   To make a command button invisible, set its Transparent property to Yes.


BorderLineStyle Property

You use the BorderLineStyle property to specify the line style of a control's border.

Note   The BorderLineStyle property is included in this version of Microsoft Access only for compatibility with previous versions. Use the BorderStyle property to specify how a control's border will appear.

Setting

The BorderLineStyle property uses the following settings.

Setting	Description	Visual Basic
Solid	(Default) Solid line	0
Dashes	Dashed line	1
Short Dashes	Dashed line with short dashes	2
Dots	Dotted line	3
Sparse Dots	Dotted line with dots spaced far apart	4
Dash Dot	Line with a dash-dot combination	5
Dash Dot Dot	Line with a dash-dot-dot combination	6
You can set this property using the control's property sheet, a macro, or Visual Basic.

Remarks

You can use this property to customize the look of your controls.

Note   The BorderLineStyle property isn't the same as the BorderStyle property, which determines whether a control's border is transparent or visible.


BorderLineStyle Property Example

You can use the following code to create a dotted border for a text box.

conDots = 3

Forms![frmCustomers]![txtLastName].BorderLineStyle = conDots


BorderWidth Property

You can use the BorderWidth property to specify the width of a control's border.

Setting

The BorderWidth property uses the following settings.

Setting	Description	Visual Basic
Hairline	(Default) The narrowest border possible on your system	0
1 pt to 6 pt	The width as indicated in points	1 to 6
You can set this property using the Formatting toolbar, a macro, or Visual Basic.

You can set the default for this property using the control's default control style.

Remarks

To use the BorderWidth property, the SpecialEffect property must be set to Flat or Shadowed and the BorderStyle property must not be set to Transparent.

The exact border width depends on your computer and printer. On some systems, the Hairline and 1-point widths appear the same.


FillColor Property

You use the FillColor property to specify the color that fills in boxes and circles drawn on reports with the Line and Circle methods. You can also use this property with Visual Basic to create special visual effects on custom reports when you print using a color printer.

Setting

The FillColor property contains a numeric expression that specifies the fill color for all boxes and circles.

You can set this property only in a macro or an Visual Basic event procedure specified by a section's OnPrint event property.

Remarks

You can use the RGB or QBColor functions to set this property. The FillColor property setting has a data type of Long.


LineSlant Property

You use the LineSlant property to specify whether a line slants from upper left to lower right or from upper right to lower left.

Setting

The LineSlant property uses the following settings.

Setting	Description	Visual Basic
\	(Default) Upper left to lower right	False (0)
/	Upper right to lower left	True (-1)
You can set this property using the control's property sheet, a macro, or Visual Basic.

Remarks

Use the LineSlant property to change a line's direction. To position and size the line on your form or report, use the mouse.


SpecialEffect Property

You can use the SpecialEffect property to specify whether special formatting will apply to a section or control.

Setting

The SpecialEffect property uses the following settings.

Setting	Example	Description	Visual Basic
Flat		The object appears flat and has the system's default colors or custom colors that were set in Design view.	0
Raised		The object has a highlight on the top and left and a shadow on the bottom and right.	1
Sunken		The object has a shadow on the top and left and a highlight on the bottom and right.	2
Etched		The object has a sunken line surrounding the control.	3
Shadow		The object has a shadow below and to the right of the control.	4
Chiseled		The object has a sunken line below the control.	5
You can set this property using the Formatting toolbar, the object's property sheet, a macro, or Visual Basic.

For controls, you can set the default for this property using the default control style of the Label button on the Control bar.

Remarks

The SpecialEffect property setting affects related property settings for the BorderStyle, BorderColor, and BorderWidth properties. For example, if the SpecialEffect property is set to Raised the settings for the BorderStyle, BorderColor, and BorderWidth properties are ignored. In addition, changing or setting the BorderStyle, BorderColor, and BorderWidth properties may cause Microsoft Access to change the SpecialEffect property setting.


Transparent Property

You can use the Transparent property to specify whether a command button is visible or transparent.

Tip   Use the BackStyle property to make other controls visible or transparent.

Setting

The Transparent property uses the following settings.

Setting	Description	Visual Basic
Yes	The button is transparent.	True (-1)
No	(Default) The button is visible.	False (0)
You can set this property in the command button's property sheet, a macro, or Visual Basic.

Remarks

You can use this property to place a transparent command button over another control. For example, you could place several transparent buttons over a picture displayed in an image frame and run various macros or Visual Basic event procedures depending which part of the picture the user clicks.

Note   To hide and disable a button, use the Visible property. To disable a button without hiding it, use the Enabled property. To hide a button only when a form or report is printed, use the DisplayWhen property.


BoundColumn Property

When you make a selection from a list box or combo box, the BoundColumn property tells Microsoft Access which column's values to use as the value of the control. If the control is bound to a field, the value in the column specified by the BoundColumn property is stored in the field named in the ControlSource property.

Setting

The BoundColumn property has the following settings.

Setting	Description

0	The ListIndex property value, rather than the column value, is stored in the current record. The ListIndex property value of the first row is 0, the second row is 1, and so on. Microsoft Access sets the ListIndex property when an item is selected from a list box or the list box portion of a combo box. Setting the BoundColumn property to 0 and using the ListIndex property value of the control might be useful if, for example, you are only interested in storing a sequence of numbers.

1 or greater	(Default) If the setting is 1 or greater, then the corresponding column value becomes the control's value. If the control is bound to a field, then this value is stored in the current record.

You can set the BoundColumn property in the object's property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note   Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, set the BoundColumn property using a number or a numeric expression equal to a value from 0 to the number set by the ColumnCount property.

Remarks

The leftmost visible column in a combo box contains the data that appears in the text box part of the combo box in Form view or in a report. The BoundColumn property determines which column in the control will be stored when you make a selection. This allows you to display different data than you store as the value of the control.

Note   If the bound column is not the same as the leftmost visible column in the control, the LimitToList property is set to Yes.

Microsoft Access uses zero-based numbers to refer to columns in the Column property. This means that if the BoundColumn property is set to 1, you could access the value stored in that column using the expression Column(0).

If the AutoExpand property is set to Yes, Microsoft Access automatically fills in a value that matches the data in the text box.


Column Property

You can use the Column property to refer to a specific column, or column and row combination, in a multiple-column combo box or list box. Use 0 to refer to the first column, 1 to refer to the second column, and so on. Use 0 to refer to the first row, 1 to refer to the second row, and so on. For example, in a list box containing a column of customer IDs and a column of customer names, you could refer to the customer name in the second column and fifth row as:

Forms![Contacts]![Customers].Column(1, 4)

Setting

The Column property uses the following settings.

Setting	Description

controlname	A string expression identifying the name of the combo box or list box control.

column	An Integer value that can range from 0 to the value of the ColumnCount property minus one.

row	Optional. An Integer value that can range from 0 to the value of the ListCount property minus one.

This property setting is only available in a macro or Visual Basic.

Remarks

You can use the Column property to assign the contents of a combo box or list box to another control, such as a text box. For example, to set the ControlSource property of a text box to the value in the second column of a list box, you could use the following expression:

= Forms![Customers]![CompanyName].Column(1)

If the user has made no selection when you refer to a column in a combo box or list box, the Column property setting will be Null. You can use the IsNull function to determine if a selection has been made as in the following example.

If IsNull(Forms![Customers]![Country]) Then MsgBox "No selection."

Note   To determine how many columns a combo box or list box has, you can inspect the ColumnCount property setting.

The Column property returns a Variant of VarType 8 (String).


Column, ColumnCount Properties Example

The following example uses the Column property and the ColumnCount property to print the values of a list box selection. Notice that if there is no selection, the value of lstCustomerNames will be Null.

Sub Read_ListBox()

Dim intNumColumns As Integer, i As Integer

Dim frmCust As Form

Set frmCust = Forms![frmCustomers]

If Not IsNull(frmCust![lstCustomerNames]) Then	  ' Any selection?

intNumColumns = frmCust![lstCustomerNames].ColumnCount

Debug.Print "The list box contains "; intNumColumns; _

IIf(intNumColumns = 1, " column", " columns"); " of data."

Debug.Print "The current selection contains:"

For i = 0 To intNumColumns - 1

Debug.Print frmCust![lstCustomerNames].Column(i)  ' Print column data.

Next i

Else

Debug.Print "You haven't selected an entry in the list box."

End If

End Sub


ColumnCount Property

You can use the ColumnCount property to specify the number of columns displayed in a list box, or in the drop-down portion of a combo box, or sent to OLE objects in a chart or object frame. For example, if you set the ColumnCount property for a list box on an Employees form to 3, one column can list last names, another can list first names, and the third can list employee ID numbers.

Setting

The ColumnCount property holds an Integer between 1 and the maximum number of fields in the table, query, or SQL statement specified in the RowSource property of the control.

You can set the ColumnCount property in the control's property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note   Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

A combo box or list box can have multiple columns. If the control's RowSource property contains the name of a table, query, or SQL statement, a combo box or list box will display the fields from that source, from left to right, up to the number specified by the ColumnCount property.

To display a different combination of fields, create either a new query or a new SQL statement for the RowSource property, specifying the fields and the order you want.

You can use the ColumnWidths property to set the width of the columns displayed in the control.


ColumnHeads Property

You can use the ColumnHeads property to display a single row of column headings for list boxes, combo boxes, and OLE objects that accept column headings. You can also use this property to create a label for each entry in a chart. What is actually displayed as the first-row column heading depends on the object's RowSourceType property.

Setting

The ColumnHeads property has the following settings.

Setting	Description	Visual Basic
Yes	Column headings are enabled and either field captions, field names, or the first row of data items are used as column headings or graph labels.	True (-1)
No	(Default) Column headings are not enabled.	False (0)
You can set the ColumnHeads property in the control's property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note   Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

The RowSourceType property specifies whether field names or the first row of data items are used to create column headings. If the RowSourceType property is set to Table/Query, the field names are used as column headings. If the field has a caption, then the caption is displayed. For example, if a list box has three columns and the RowSourceType property is set to Table/Query, the first three field names are used as headings. If the RowSourceType property is set to Value List, the first row of data items entered in the Value List will be column headings.

When the first row of data items are used as column headings, they can't be selected.

Headings in combo boxes appear only when the list drops down.


ColumnWidths Property

You can use the ColumnWidths property to specify the width of each column in a multiple-column combo box or list box.

Setting

The ColumnWidths property holds a value specifying the width of each column in inches or centimeters, depending on the measurement system selected in the Regional Settings section of the Windows Control Panel. The default setting is 1 inch or 2.54 centimeters.

To separate your column entries, use semicolons (;) as list separators (or the list separator selected in the Regional Settings section of the Windows Control Panel).

A width of 0 hides a column. Any or all of the ColumnWidths property settings can be blank. You create a blank setting by typing a list separator without a preceding value. Blank values result in Microsoft Access automatically setting a default column width that varies depending on the number of columns and the width of the combo box or list box.

Note   In a combo box, the first visible column is displayed in the text box portion of the control.

You can set the ColumnWidths property in a combo box or list box's property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note   Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, use a string expression to set the column width value in twips. Column widths are separated by semicolons. To specify a different unit of measurement include the unit of measure. For example, the following string expression specifies three column widths in centimeters.

"6 cm;0;6 cm"

Remarks

If you leave the ColumnWidths property setting blank, Microsoft Access uses the default width. If the width of the control is greater than the width of the displayed columns, Microsoft Access sets the width of each column as the overall width of the list box or combo box divided by the number of columns. If the column widths you set are too wide to be fully displayed within the combo box or list box, the rightmost columns are hidden and a horizontal scroll bar appears.

If you specify the width for some columns but leave the setting for others blank, Microsoft Access divides the remaining width by the number of columns for which you haven't specified a width. The minimum calculated column width is 1,440 twips (1 inch).

For example, the following settings are applied to a 4-inch list box.

Setting	Description

1.5 in;0;2.5 in	The first column is 1.5 inches, the second column is hidden, and the third column is 2.5 inches.

2 in;;2 in	The first column is 2 inches, the second column is 1 inch (default), and the third column is 2 inches. Because only half of the third column is visible, a horizontal scroll bar appears.

(Blank)	The three columns are the same width (1.33 inches).

Note   This property is different than the ColumnWidth property, which specifies the width of a specified column in a datasheet.


LimitToList Property

You can use the LimitToList property to limit a combo box's values to the listed items.

Setting

The LimitToList property has the following settings.

Setting	Description	Visual Basic
Yes	If the user selects an item from the list in the combo box or enters text that matches a listed item, Microsoft Access accepts it. Entered text that doesn't match a listed item isn't accepted. The user must retype the entry, select a listed item, press ESC, or click Undo on the Edit menu.	True (-1)
No	(Default) Microsoft Access accepts any text that conforms to the ValidationRule property.	False (0)
You can set the LimitToList property in the combo box's property sheet, a macro, or Visual Basic.

For table fields, you can set this property in table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Note   Microsoft Access sets this property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

When the LimitToList property of a bound combo box is set to No, you can enter a value in the combo box that isn't included in the list. Microsoft Access stores the new value in the form's underlying table or query, not the table or query set for the combo box by the RowSource property. To have newly entered values appear in the combo box, you must add the new value to the table or query set in the RowSource property using a macro or Visual Basic event procedure.

Setting both the LimitToList property and the AutoExpand property to Yes lets Microsoft Access find matching values from the list as the user enters characters in the text box portion of the combo box.

When the LimitToList property is set to Yes and the user enters a combo box initialized with a non-Null value, Microsoft Access will not allow the user to exit the combo box without having made a selection. If the combo box is initialized with a Null value, the user may make a selection, clear that selection and exit the control leaving a Null value.

Note   If you set the combo box's BoundColumn property to any column other than the first visible column, then the LimitToList property is automatically set to Yes.


AllowEditing, DefaultEditing Properties

AllowEditing [image] determines whether the Allow Editing command on the Records menu is enabled when you open a form in Form view or Datasheet view.

DefaultEditing [image] determines whether a form opens to allow editing, read-only access, data entry (you can only enter new records), or editing of existing records only (you can't enter any new records).

Note   The AllowEditing and DefaultEditing properties are included in this version of Microsoft Access only for compatibility with previous versions. It is recommended that you use the AllowEdits, AllowAdditions, and DataEntry properties instead.

Setting

The AllowEditing property uses the following settings.

Setting	Description
Available	(Default) The Allow Editing command on the Records menu is enabled.
Unavailable	The Allow Editing command is disabled.
The DefaultEditing property uses the following settings.

Setting	Description
Allow Edits	(Default) You can edit, add, or delete records in the form's table or query.
Read Only	You can't edit, add, or delete records until you choose the Allow Editing command.
Data Entry	You can add new records. Existing records aren't available.
Can't Add Records	You can edit or delete existing records. You can't add new records.
You can set these properties in the form's property sheet, a macro or Visual Basic.

Remarks

Use these properties to design forms for data entry or for read-only access. You can combine them to establish the following conditions.

DefaultEditing	AllowEditing	Description
Allow Edits	Available or Unavailable	All records are available. You can edit, add, or delete records.
Read Only	Available	All records are available. You must choose the Allow Editing command to edit, add, or delete records.
	Unavailable	All records are available. You can't edit, add, or delete records.
Data Entry	Available	No existing records are available. You can add new records.
	Unavailable	No existing records are available. You can't edit, add, or delete records.
Can't Add Records	Available or Unavailable	All existing records are available, and you can edit or delete them. You can't add new records.
Note   The Data Entry setting doesn't completely prevent you from viewing records when using the form. If the AllowFilters property is set to Yes, you can click Remove Filter/Sort on the Records menu to display all records.


AllowEditing, DefaultEditing Properties Example

The following example disables the Records menu's Allow Editing command and specifies that the form open in data entry mode.

Sub Form_Open(Cancel As Integer)

Const conDataEntry = 3

Me.AllowEditing = False	  ' Disable Records Menu Option.

Me.DefaultEditing = conDataEntry

End Sub


AutoTab Property

You can use the AutoTab property to specify whether an automatic tab occurs when the last character permitted by a text box control's input mask is entered. An automatic tab moves the focus to the next control in the form's tab order.

Setting

The AutoTab property uses the following settings.

Setting	Description	Visual Basic
Yes	Generates a tab when the last allowable character in a text box is entered.	True (-1)
No	(Default) Doesn't generate a tab when the last allowable character in a text box is entered.	False (0)
You can set this property using the control's property sheet, a macro, or Visual Basic.

You can also set this property using the control's default control style.

The AutoTab property affects tab behavior in both Form view and Datasheet view.

Remarks

You create an input mask for a control using the InputMask property.

You can also create an input mask for a text box control bound to a field by setting the InputMask property for the field in the form's underlying table or query. If the field is dragged to a form from the field list, the field's input mask is inherited by the text box control.

You could use the AutoTab property if you have a text box on a form for which you usually enter the maximum number of characters for each record. Once the maximum number of characters are entered, focus automatically moves to the next control in the tab order. For example, you could use this property for a CategoryType field that must always be five characters long.


Enabled, Locked Properties

Enabled [image] You can use this property to specify whether a control can have the focus in Form view.

Locked [image] You can use this property to specify whether you can edit data in a control in Form view.

Setting

The Enabled property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default for all controls except unbound object frames) The control can have the focus. If the control is an unbound object frame, double-clicking it executes the control's primary verb. For example, an unbound object frame could play an embedded sound object.	True (-1)
No	(Default for unbound object frames) The control can't have the focus and appears dimmed. If the control is an option group, neither the option group nor the controls inside the option group can have the focus.	False (0)
The Locked property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default for unbound object frames) The control functions normally but doesn't allow editing, adding, or deleting data.	True (-1)
No	(Default for all controls except unbound object frames) The control functions normally and allows editing, adding, and deleting data.	False (0)
You can set this property in the control's property sheet, a macro, or Visual Basic.

Remarks

Use the Enabled property to enable and disable controls. For example, in Form view you can disable a command button until you have changed data in a text box control. You can then use the control's AfterUpdate event to call an event procedure or macro to enable the command button.

Use the Locked property to protect data in a field by making it read-only. For example, you might want a control only to display information without allowing editing, or you might want to lock a control until a specific condition is met.

You can combine the Enabled and Locked property settings to achieve the following effects.

Enabled	Locked	Effect
Yes	Yes	The control can have the focus. Data is displayed normally and can be copied but not edited.
Yes	No	The control can have the focus. Data is displayed normally and can be copied and edited.
No	Yes	The control can't have the focus. Data is displayed normally but can't be copied or edited.
No	No	The control can't have the focus. Control and data are disabled (gray).
The TabStop property can be combined with the Enabled property to prevent the use of the TAB key to select a command button, while still allowing use of the button by clicking on it. Setting the TabStop property to No means that the command button won't be in the tab order. However, if the Enabled property is set to Yes, then you can still click the command button.

To allow edits to an embedded or linked object in an unbound object frame, you must set the Enabled property for the unbound object frame to Yes and the Locked property to No.


Enabled, Locked Properties Example

The following example toggles the Enabled property of a command button and the Enabled and Locked properties of a control depending on the type of Employee displayed in the current record. If the employee is a manager, then the SalaryDetails button is enabled and the PersonalInfo control is unlocked and enabled.

Sub Form_Current()

If Me!EmployeeType = "Manager" Then

Me!SalaryDetails.Enabled = True

Me!PersonalInfo.Enabled = True

Me!PersonalInfo.Locked = False

Else

Me!SalaryDetails.Enabled = False

Me!PersonalInfo.Enabled = False

Me!PersonalInfo.Locked = True

End If

End Sub


Enabled, Locked Properties - Applies To
Enabled, Locked Properties — Applies To

Enabled Property

Locked Property


EnterKeyBehavior Property

You can use the EnterKeyBehavior property to specify what happens when you press ENTER in a text box control in Form view or Datasheet view. For example, you can use the EnterKeyBehavior property if you have a control bound to a Memo field in a table to make entering multiple-line text easier. If you don't set this property to New Line In Field, you must press CTRL+ENTER to enter a new line in the text box.

Setting

The EnterKeyBehavior property uses the following settings.

Setting	Description	Visual Basic
Default	(Default) Microsoft Access uses the result specified in the Move After Enter option on the Keyboard tab of the Options dialog box, available by clicking Options on the Tools menu. For details, see the Remarks section.	False (0)
New Line In Field	Pressing ENTER in the control creates a new line in the control so you can enter additional text.	True (-1)
You can set this property in the control's property sheet, a macro, or Visual Basic.

You can also set this property using the control's default control style.

Remarks

If you set the EnterKeyBehavior property to Default, Microsoft Access uses the setting for the Move After Enter option on the Keyboard tab in the Options dialog box, available by clicking Options on the Tools menu. The Move After Enter section has the following settings.

Setting	Description

Don't Move	Pressing ENTER has no effect.

Next Field	Pressing ENTER moves the insertion point to the next control or field in the form or datasheet in the Tab order.

Next Record	Pressing ENTER moves the insertion point to the first control or field in the next record on the form or datasheet.


RecordLocks Property

You can use the RecordLocks property to determines how records are locked and what happens when two users try to edit the same record at the same time. When you edit a record, Microsoft Access can automatically lock that record to prevent other users from changing it before you are finished.

Forms [image] You can use this property to specify how records in the underlying table or query are locked when data in a multiuser database is updated.

Reports [image] You can use this property to specify whether records in the underlying table or query are locked while a report is previewed or printed.

Queries [image] You can use this property to specify whether records in a query (typically an action query in a multiuser database) are locked while the query is run.

Setting

The RecordLocks property uses the following settings.

Setting	Description	Visual Basic
No Locks	(Default) In forms, two or more users can edit the same record simultaneously. This is also called "optimistic" locking. If two users attempt to save changes to the same record, Microsoft Access displays a message to the user who tries to save the record second. This user can then discard the record, copy the record to the Clipboard, or replace the changes made by the other user. This setting is typically used on read-only forms or in single-user databases. It is also used in multiuser databases to permit more than one user to be able to make changes to the same record at the same time. In reports, records aren't locked while the report is previewed or printed. In queries, records aren't locked while the query is run.	0
All Records	All records in the underlying table or query are locked while the form is open in Form view or Datasheet view, while the report is previewed or printed, or while the query is run. Although users can read the records, no one can edit, add, or delete any records until the form is closed, the report has finished printing, or the query has finished running.	1
Edited Record	(Forms and queries only) A page of records is locked as soon as any user starts editing any field in the record and stays locked until the user moves to another record. Consequently, a record can be edited by only one person at a time. This is also called "pessimistic" locking.	2
You can set this property using the objects property sheet, a macro, or Visual Basic.

Remarks

You can use the No Locks setting for forms if only one person uses the underlying tables or queries or makes all the changes to the data.

In a multiuser database, you can use the No Locks setting if you want to use optimistic locking and warn users attempting to edit the same record on a form. You can use the Edited Record setting if you want to prevent two or more users editing data at the same time.

You can use the All Records setting when you need to ensure that no changes are made to data after you start to preview or print a report or run an append, delete, make-table, or update query.

In Form view or Datasheet view, each locked record has a locked symbol [image] in its record selector.

Note   To change the default RecordLocks property setting for forms, click Options on the Tools menu. Click the Advanced tab on the Options dialog box and select the Default Record Locking option.

Data in a form, report, or query from an Open Database Connectivity (ODBC) database is treated as if the No Locks setting were chosen, regardless of which setting is actually chosen.


RecordsetType Property

You can use the RecordsetType property to specify what kind of recordset is made available to a form. For example, if you don't want data in bound controls to be edited when a form is in Form view or Datasheet view, you can set the RecordsetType property to Snapshot.

Note   For forms, the RecordsetType property replaces the AllowUpdating property found in Microsoft Access 2.0. Microsoft Access for Windows 95 supports the AllowUpdating property for backwards compatibility only. It is recommended that you use the RecordsetType property.

Setting

The RecordsetType property uses the following settings.

Setting	Description	Visual Basic
Dynaset	(Default) You can edit bound controls based on a single table or tables with a one-to-one relationship. For controls bound to fields based on tables with a one-to-many relationship, you can't edit data from the join field on the "one" side of the relationship unless cascade update is enabled between the tables. For more information see, Updating data.	0
Dynaset (Inconsistent Updates)	All tables and controls bound to their fields can be edited.	1
Snapshot	No tables or the controls bound to their fields can be edited.	2
You can set this property using the form's property sheet, a macro, or Visual Basic.

Remarks

You can create forms based on multiple underlying tables with fields bound to controls on the forms. Depending on the RecordsetType property setting, you can limit which of these bound controls can be edited.

In addition to the editing control provided by RecordsetType, each control on a form has a Locked property that you can set to specify whether the control and its underlying data can be edited. If the Locked property is set to Yes, you can't edit the data.


RecordsetType Property Example

In the following example, only if the user ID is ADMIN can records be updated. This code sample sets the RecordsetType property to Snapshot if the global variable gstrUserID value is not ADMIN.

Sub Form_Open(Cancel As Integer)

Const conSnapshot = 2

If gstrUserID <> "ADMIN" Then

Forms!Employees.RecordsetType = conSnapshot

End If

End Sub


Value Property (Microsoft Access)

You can use the Value property to determine or specify if a control is selected, the selected value or option within the control, or the text contained in a text box control.

Check box, option button, and toggle button controls [image] You can use this property to determine or specify whether or not the control is selected.

Combo box, list box, and option group controls [image] You can use this property to determine or specify which value or option in the control is selected.

Text box controls [image] You can use this property to determine or specify the text in the text box.

Setting

The Value property uses the following setting depending on the specified control.

Control	Setting	Description	Visual Basic
Check box	True False	The check box is selected (Default) The check box is cleared.	True (-1) False (0)
Combo box	The text in the text box portion of the control.	This may or may not be the same as the setting for the Text property of the control. The current setting for the Text property is what is displayed in the text box portion of the combo box; the Value property is set to the Text property setting only after this text is saved.
List box	List box item value	The value in the bound column for the item selected in the list.
Option button	True False	The option button is selected (Default) The option button isn't selected.	True (-1) False (0)
Option group	OptionValue property setting	The OptionValue property setting for the selected control in the group.
Text box	The value of the control's Text property	The Text property returns the formatted string. The Text property may be different than the Value property for a text box control. The Text property is the current contents of the control. The Value property is the saved value of the text box control. The Text property is always be current while the control has the focus.
Toggle button	True	The toggle button is selected (pressed in).	True (-1)
	False	The toggle button isn't selected (not pressed in).	False (0)
You can set this property using only a macro or Visual Basic.

Remarks

The Value property returns or sets a control's default property, which is the property that is assumed when you don't explicitly specify a property name. For example, because the default value of a text box is the value of the Text property, you can refer to its Text property setting without explicitly specifying the name of the property with the following code.

Forms!frmCustomers!txtLastName = "Smith"

This means that the following two statements are equivalent text.

Forms!frmCustomers!optCreditApproved.Value = True

Forms!Form1!optCreditApproved = True

Note   The Value property is not the same as the DefaultValue property, which specifies the value that a property is assigned when a new record is created.


Value Property Example

The following example shows how you can call one of two procedures, depending whether the Credit check box on the Customers form is selected or cleared.

Sub PaymentType()

If Forms!Customers!Credit.Value = False Then

ProcessCash

ElseIf Forms!Customers!Credit.Value = True Then

ProcessCredit

End If

End Sub


DefaultValue Property (Microsoft Access)

You can use the DefaultValue property to specify a value that is automatically entered in a field when a new record is created. For example, in an Addresses table you can set the default value for the City field to New York. When users add a record to the table, they can either accept this value or enter the name of a different city.

Notes

The DefaultValue property doesn't apply to check box, option button, or toggle button controls when contained in an option group. It does apply to the option group itself.

The DefaultValue property applies to all table fields except those fields with the data type of AutoNumber or OLE Object.

Setting

The DefaultValue property specifies text or an expression that is automatically entered in a field when a new record is created. For example, if you set the DefaultValue property for a text box control to = Now(), the control displays the current time. The maximum length for a DefaultValue property setting is 255 characters.

You can set this property in the property sheet in table Design view (under Field Properties), a macro, or Visual Basic.

In Visual Basic, use a string expression to set the value of this property. For example, the following sets the DefaultValue property for a text box control named PaymentMethod to "Cash".

Forms!frmInvoice!PaymentMethod.DefaultValue = """Cash"""

Note	To set this property for a field using Visual Basic, use the Data Access Objects DefaultValue property.

Remarks

If you create a control by dragging a field from the field list, the field's DefaultValue property setting, as defined in the table, is applied to the control on the form.

One control can provide the default value for another control. For example, if you set the DefaultValue property for a control to the following expression, the field's default value is set to the DefaultValue property setting for the txtShipTo control.

= Forms![frmInvoice]![txtShipTo]

If the controls are on the same form, the control that is the source of the default value must appear earlier in the tab order than the control containing the expression.

The DefaultValue property is applied only when you add a new record. If you change the DefaultValue property, the change is not automatically applied to existing records.

If you set the DefaultValue property for a control on a form for a field that also has a DefaultValue property setting defined in the table, the control setting overrides the table setting.


Format Property

You can use the Format property to customize the way numbers, dates, times, and text are displayed and printed. For example, if you've created a Price text box control, you can set its Format property to Currency. If you enter 4321.678 in the control, the number would be displayed as $4,321.68.

Setting

The Format property uses different settings for different data types. For information about settings for a specific data type, select one of the following topics.

Number and Currency Data Types

Date/Time Data Types

Yes/No Data Types

Text and Memo Data Types

For a control, you can set this property in the control's property sheet. For a field, you can set this property in table Design view (under Field Properties) or in Design view of the Query window (in the Field Properties property sheet). You can also use a macro or Visual Basic.

You can use one of the predefined formats or you can create a custom format using formatting symbols.

Note   In Visual Basic, enter a string expression that corresponds to one of the predefined formats or enter a custom format.

Remarks

The Format property affects only how data is displayed. It does not affect how data is stored.

Microsoft Access provides predefined formats for Number, Date/Time, Yes/No, and Text and Memo data types. The predefined formats depend on the country specified in the Regional Settings section of the Windows Control Panel. Microsoft Access displays formats appropriate for the country selected. For example, with the United States indicated in the Regional Settings tab, 1234.56 in the Currency format appears as $1,234.56; but when the United Kingdom is indicated in the Regional Settings tab, the number appears as £1,234.56.

If you set a field's Format property in table Design view, Microsoft Access uses that format to display data in datasheets. It also applies the field's Format property to new controls on forms and reports.

You can use the following symbols in custom formats for any data type.

Symbol	Meaning

(space)	Display spaces as literal characters.

"ABC"	Display anything inside quotation marks as literal characters.

!	Force left alignment instead of right alignment.

*	Fill available space with the next character.

\	Display the next character as a literal character. You can place quotation marks around literal characters.

[color]	Display in the color named between the brackets. Available colors: Black, Blue, Green, Cyan, Red, Magenta, Yellow, White.

You can't mix custom formatting symbols for Number data types with Date/Time or with Text formatting symbols.

When you have defined an input mask and set the Format property for the same data, the Format property takes precedence when the data is displayed and the input mask is ignored. For example, if you create a Password input mask in table Design view and also enter the Format property, either in the table or in a control on a form, the Password input mask is ignored and the data is displayed according to the Format property.


Format Property Example

The following three examples set the Format property using a predefined format.

Me![Date].Format = "Medium Date"

Me![Time].Format = "Long Time"

Me![Registered].Format = "Yes/No"

The next example sets the Format property using a custom format. This format displays a date as: Jan 1995.

Forms![Employees]![HireDate].Format = "mmm yyyy"

This example demonstrates a Visual Basic function that formats numeric data with the Currency format and formats text data entirely in capital letters. The function is called from the OnLostFocus event of an unbound control named TaxRefund.

Function FormatValue () As Integer

Dim varEnteredValue As Variant

varEnteredValue = Forms!Survey!TaxRefund.Value

If IsNumeric(varEnteredValue) = True Then

Forms!Survey!TaxRefund.Format = "Currency"

Else

Forms!Survey!TaxRefund.Format = ">"

End If

End Function


Format Property - Number and Currency Data Types
Format Property — Number and Currency Data Types

You can set the Format property to predefined number formats or custom number formats for number and currency data types.

Setting

Predefined Formats

The following table shows the predefined Format property settings for numbers.

Setting	Description

General Number	(Default) Display the number as entered.

Currency	Use the thousand separator; display negative numbers enclosed in parentheses; the default DecimalPlaces property setting is 2.

Fixed	Display at least one digit; the default DecimalPlaces property setting is 2.

Standard	Use the thousand separator; the default DecimalPlaces property setting is 2.

Percent	Multiply the value by 100 and append a percent sign (%); the default DecimalPlaces property setting is 2.

Scientific	Use standard scientific notation.

Custom Formats

You can create custom number formats using the following symbols.

Symbol	Description

. (period)	Decimal separator. Separators are set in the Regional Settings section of the Windows Control Panel.

, (comma)	Thousand separator.

0	Digit placeholder. Display a digit or 0.

#	Digit placeholder. Display a digit or nothing.

$	Display the literal character $.

%	Percentage. The value is multiplied by 100 and a percent sign is appended.

E- or e-	Scientific notation with a minus sign (-) next to negative exponents and nothing next to positive exponents. It must be used with other symbols, as in 0.00E-00 or 0.00E00.

E+ or e+	Scientific notation with a minus sign next to negative exponents and a plus sign (+) next to positive exponents. It must be used with other symbols, as in 0.00E+00.

Custom number formats can have one to four sections with semicolons (;) as the list separator. Each section contains the format specification for a different type of number.

Section	Description

First	The format for positive numbers.

Second	The format for negative numbers.

Third	The format for zero values.

Fourth	The format for Null values.

For example, the standard Currency format has the following pattern.

$#,##0.00;($#,##0.00)[Red]

This number format contains two sections separated by a semicolon and uses one format for positive numbers (determined by the first section) and another for negative numbers (determined by the second section). Since the third and fourth sections are omitted, zero or Null values are not formatted in a special way.

Remarks

You can use the DecimalPlaces property to display a different number of decimal places than the Format property specifies.


Format Property - Number and Currency Data Types Example
Format Property — Number and Currency Data Types Example

The following are examples of the predefined number formats.

Setting	Data	Display
General Number	3456.789 -3456.789 $213.21	3456.789 -3456.789 $213.21
Currency	3456.789 -3456.789	$3,456.79 ($3,456.79)
Fixed	3456.789 -3456.789 3.56645	3456.79 -3456.79 3.57
Standard	3456.789	3,456.79
Percent	3 0.45	300% 45%
Scientific	3456.789 -3456.789	3.46E+03 -3.46E+03
The following are examples of custom number formats.

Setting	Description

0;(0);;"Null"	Display positive values normally; display negative values in parentheses; display nothing if the value is zero; display the word "Null" if the value is Null.

+0.0;-0.0;0.0	Display a plus (+) or minus (-) sign with positive or negative numbers; display 0.0 if the value is zero or Null.


Format Property - Date/Time Data Types
Format Property — Date/Time Data Types

You can set the Format property to predefined date and time formats or custom formats for date/time data types.

Setting

Predefined Formats

The following table shows the predefined Format property settings for Date/Time data types.

Setting	Description

General Date	(Default) If the value is a date only, no time is displayed; if the value is a time only, no date is displayed. This setting is a combination of the Short Date and the Long Time settings.
Examples: 4/3/93, 05:34:00 PM, and 4/3/93 05:34:00 PM.

Long Date	Same as the Long Date setting in the Regional Settings section of the Windows Control Panel.
Example: Saturday, April 3, 1993.

Medium Date	Example: 03-Apr-93.

Short Date	Same as the Short Date setting in the Regional Settings section of the Windows Control Panel.
Example: 4/3/93.

Long Time	Same as the Time setting in the Regional Settings section of the Windows Control Panel.
Example: 5:34:23 PM.

Medium Time	Example: 05:34 PM.

Short Time	Example: 17:34.

Custom Formats

You can create custom date and time formats using the following symbols.

Symbol	Description

: (colon)	Time separator. Separators are set in the Regional Settings section of the Windows Control Panel.

/	Date separator. Separators are set in the Regional Settings section of the Windows Control Panel.

c	Same as the General Date predefined format.

d	Day of the month in one or two numeric digits, as needed (1 to 31).

dd	Day of the month in two numeric digits (01 to 31).

ddd	First three letters of the weekday (Sun to Sat).

dddd	Full name of the weekday (Sunday to Saturday).

ddddd	Same as the Short Date predefined format.

dddddd	Same as the Long Date predefined format.

w	Day of the week (1 to 7).

ww	Week of the year (1 to 53).

m	Month of the year in one or two numeric digits, as needed (1 to 12).

mm	Month of the year in two numeric digits (01 to 12).

mmm	First three letters of the month (Jan to Dec).

mmmm	Full name of the month (January to December).

q	Date displayed as the quarter of the year (1 to 4).

y	Number of the day of the year (1 to 366).

yy	Last two digits of the year (01 to 99).

yyyy	Full year (0100 to 9999).

h	Hour in one or two digits, as needed (0 to 23).

hh	Hour in two digits (00 to 23).

n	Minute in one or two digits, as needed (0 to 59).

nn	Minute in two digits (00 to 59).

s	Second in one or two digits, as needed (0 to 59).

ss	Second in two digits (00 to 59).

ttttt	Same as the Long Time predefined format.

AM/PM	Twelve-hour clock with the uppercase letters AM or PM, as appropriate.

am/pm	Twelve-hour clock with the lowercase letters am or pm, as appropriate.

A/P	Twelve-hour clock with the uppercase letter A or P, as appropriate.

a/p	Twelve-hour clock with the lowercase letter a or p, as appropriate.

AMPM	Twelve-hour clock with the appropriate morning/afternoon designator as defined in the Regional Settings section of the Windows Control Panel.

Note   If you want to add a comma or other separator to your custom format, enclose the separator in quotation marks like this: mmm d", "yyyy.


Format Property - Date/Time Data Types Example
Format Property — Date/Time Data Types Example

The following are examples of custom date/time formats.

Setting	Display

ddd", "mmm d", "yyyy	Mon, Jun 2, 1996

mmmm dd", "yyyy	June 02, 1996

"This is week number "ww	This is week number 22

"Today is "dddd	Today is Tuesday


Format Property - Yes/No Data Types
Format Property — Yes/No Data Types

You can set the Format property to Yes/No, True/False, or On/Off predefined formats or a custom format for Yes/No data types.

Setting

Predefined Formats

The Format property provides the Yes/No, True/False, and On/Off predefined formats. Yes, True, and On are equivalent, as are No, False, and Off. If you specify one predefined format and then enter an equivalent value, the predefined format of equivalent value will be displayed. For example, if you enter True or On in a text box control with its Format property set to Yes/No, the value is automatically converted to Yes.

Custom Formats

Yes/No data types use custom formats containing up to three sections.

Section	Description

First	This section has no effect on Yes/No data types. However, a semicolon (;) is required as a placeholder.

Second	The text to display in place of Yes, True, or On values.

Third	The text to display in place of No, False, or Off values.


Format Property - Yes/No Data Types Example
Format Property — Yes/No Data Types Example

The following example shows a custom format that displays the word "Always" in blue text for Yes, True, or On, and the word "Never" in red text for No, False, or Off.

;"Always"[Blue];"Never"[Red]


Format Property - Text and Memo Data Types
Format Property — Text and Memo Data Types

You can set the Format property to create custom formats for Text and Memo fields using special symbols.

Setting

The Format property uses the following symbols to define text and memo data types.

Symbol	Description

@	Text character (either a character or a space) is required.

&	Text character is not required.

<	Force all characters to lowercase.

>	Force all characters to uppercase.

Custom formats for Text and Memo fields can have up to three sections. Each section contains the format specification for different data in a field.

Section	Description

First	Format for fields with text.

Second	Format for fields with zero-length strings.

Third	Format for fields with Null values.

If you specify only two sections, the second section refers to fields with zero-length strings and Null values.

For example, if you have a text box control in which you want the word "None" to appear when there is no string in the field, you could enter the custom format @;"None";"Null" as the control's Format property setting. The @ symbol causes the text from the field to be displayed; the second section causes the word "None" to appear when there is a zero-length string in the field, the third section causes the word "Null" to appear when there is a Null value in the field.


Format Property - Text and Memo Data Types Example
Format Property — Text and Memo Data Types Example

The following are examples of Text and Memo custom formats.

Setting	Data	Display
@@@-@@-@@@@	465043799	465-04-3799
@@@@@@@@@	465-04-3799 465043799	465-04-3799 465043799
>	davolio DAVOLIO Davolio	DAVOLIO DAVOLIO DAVOLIO
<	davolio DAVOLIO Davolio	davolio davolio davolio
@;;"Unknown"	Null value	Unknown
	Zero-length string	Nothing is displayed
	Any text	Same text as entered is displayed


InputMask Property

You can use the InputMask property to make data entry easier and control the values users can enter in a text box control. For example, you could create an input mask for a Phone Number field that shows you exactly how to enter a new number: (___) ___-____. It is often easier to use the Input Mask Wizard to set the property for you.

Setting

The InputMask property can contain up to three sections separated by semicolons (;).

Section	Description

First	Specifies the input mask itself (for example, (999) 000-0000!). For a list of characters you can use to define the input mask, see the following table.

Second	Specifies whether Microsoft Access stores the literal display characters in the table when you enter data. If you use 0 for this section, all literal display characters (for example, the parentheses in a phone number input mask) are stored with the value; if you enter 1 or leave this section blank, only characters typed into the control are stored.

Third	Specifies the character that Microsoft Access displays for the space where you should type a character in the input mask. For this section, you can use any character; to display an empty string, use a space enclosed in quotation marks (" ").

In Visual Basic you use a string expression to set this property. For example, the following specifies an input mask for a text box control used for entering telephone:

Forms![Customers]![Telephone].InputMask = "(###) ###-####"

When you create an input mask, you can require that certain data be entered (for example, the area code for a phone number) and that other data is optional (such as a telephone extension) by using special characters. These characters specify the type of data, such as a number or character, that you must enter for each character in the input mask.

You can define an input mask using the following characters.

Character	Description

0	Digit (0 to 9, entry required, plus (+) and minus (-) signs not allowed).

9	Digit or space (entry not required, plus and minus signs not allowed).

#	Digit or space (entry not required, spaces are displayed as blanks while in Edit mode, but blanks are removed when data is saved, plus and minus signs allowed).

L	Letter (A to Z, entry required).

?	Letter (A to Z, entry optional).

A	Letter or digit (entry required).

a	Letter or digit (entry optional).

&	Any character or a space (entry required).

C	Any character or a space (entry optional).

.  ,  :  ;  -  /	Decimal placeholder and thousand, date, and time separators. (The actual character used depends on the settings in the Regional Settings section of the Windows Control Panel).

<	Causes all characters to be converted to lowercase.

>	Causes all characters to be converted to uppercase.

!	Causes the input mask to display from right to left, rather than from left to right, when characters on the left side of the input mask are optional. Characters typed into the mask always fill it from left to right. You can include the exclamation point anywhere in the input mask.

\	Causes the character that follows to be displayed as the literal character (for example, \A is displayed as just A).

Note   Setting the InputMask property to the word "Password" creates a password-entry control. Any character typed in the control is stored as the character but is displayed as an asterisk (*). You use the Password input mask to prevent displaying the typed characters on the screen.

For a control, you can set this property in the control's property sheet. For a field in a table, you can set the property in table Design view (under Field Properties) or in Design view of the Query window (in the Field Properties property sheet).

You can also set the InputMask property in a macro or Visual Basic.

Remarks

When you type data in a field for which you've defined an input mask, the data is always entered in Overtype mode. If you use the BACKSPACE key to delete a character, the character is replaced by a blank space.

If you move text from a field for which you've defined an input mask onto the Clipboard, the literal display characters are copied, even if you have specified that they be saved with data.

Note   Only characters that you type directly in a control or combo box are affected by the input mask. Microsoft Access ignores any input masks when you import data, run an action query, or enter characters in a control using Visual Basic by setting the control's Text property or in a macro using the SetValue action.

When you've defined an input mask and set the Format property for the same field, the Format property takes precedence when the data is displayed. This means that even if you've saved an input mask, the input mask is ignored when data is formatted. The data in the underlying table itself isn't changed; the Format property affects only how the data is displayed.


InputMask Property Example - Useful Input Masks
InputMask Property Example — Useful Input Masks

The following table shows some useful input masks and the type of values you can enter into them.

Input mask	Sample values

(000) 000-0000	(206) 555-0248

(999) 000-0000!	(206) 555-0248
(   ) 555-0248

(000) AAA-AAAA	(206) 555-TELE

#999	-20
2000

>L????L?000L0	GREENGR339M3
MAY  R 452B7

>L0L 0L0	T2F 8M4

00000-9999	98115-
98115-3007

>L<??????????????	Maria
Brendan

ISBN 0-&&&&&&&&&-0	ISBN 1-55615-507-7
ISBN 0-13-964262-5

>LL00000-0000	DB51392-0493


ValidationRule, ValidationText Properties (Microsoft Access)

You can use the ValidationRule property to specify requirements for data entered into a field or control. When data is entered that violates the ValidationRule setting, you can specify the message to be displayed to the user by setting the ValidationText property.

Note   The ValidationRule and ValidationText properties do not apply to check box, option button, or toggle button controls when they are in an option group. They apply only to the option group itself.

Setting

Enter an expression for the ValidationRule property setting and text for the ValidationText property setting. The maximum length for each property setting is 255 characters.

For controls, you can set the property to any valid expression. For field and record validation rules, the expression can't contain user-defined functions, domain or aggregate functions, the CurrentUser or Eval function, or references to forms, queries, or tables. In addition, field validation rules can't contain references to other fields. For records, expressions can include references to fields in that table.

You can set the ValidationRule and ValidationText properties in:

The lower portion of table Design view (for a field validation rule).

The property sheet for a table (for a record validation rule).

The property sheet for a control on a form.

A macro or Visual Basic. In Visual Basic, use a string expression to set these properties.

Note	For table fields and records, you can also set these properties in Visual Basic by using the Data Access Objects ValidationRule property.

Remarks

Microsoft Access automatically validates values based on a field's data type; for example Microsoft Access doesn't allow text in a numeric field. You can set more specific rules using the ValidationRule property.

If you set the ValidationRule property but not the ValidationText property, Microsoft Access displays a standard error message when the validation rule is violated. If you set the ValidationText property, the text you enter is displayed as the error message.

For example, when a record is added for a new employee, you can enter a ValidationRule property requiring that the employee Start Date field fall between the company's founding date and the current date. If the date entered isn't in this range, you can display the ValidationText property message: "Start date is incorrect."

If you create a control by dragging a field from the field list, the field's validation rule remains in effect, although it isn't displayed in the control's ValidationRule property box in the property sheet. This is because a field's validation rule is inherited by a control bound to that field.

Control, field, and record validation rules are applied as follows:

Validation rules you set for fields and controls are applied when you edit the data and the focus leaves the field or control.

Validation rules for records are applied when you move to another record.

If you create validation rules for both a field and a control bound to the field, both validation rules are applied when you edit data and the focus leaves the control.

The following table contains expression examples for the ValidationRule and ValidationText properties.

ValidationRule property	ValidationText property
<> 0	Entry must be a non-zero value.
> 1000 Or Is Null	Entry must be blank or greater than 1000.
Like "A????"	Entry must be 5 characters and begin with the letter A.
>= #1/1/95# And <#1/1/96#	Entry must be a date in 1995.
DLookup("[CustomerID]", "Customers", "[CustomerID] = Forms![Customers]![CustomerID]") Is Null	Entry must be unique CustomerID (form-level validation only).
If you create a validation rule for a field, Microsoft Access doesn't normally allow a Null value to be stored in the field. If you want to allow a Null value, add Is Null to the validation rule, as in "<> 8 Or Is Null".

You can't set field or record validation rules for tables created outside Microsoft Access (for example, dBASE, Paradox, and SQL Server). For these kinds of tables, you can create validation rules for controls only.


ValidationRule, ValidationText Properties Example

The following example creates a validation rule for a Field that allows only values over 65 to be entered. If a number less than 65 is entered, a message is displayed. The properties are set using the SetFieldValidation function.

Dim strTblName As String, strFldName As String
Dim strValidRule As String, strValidText As String, intX As Integer
strTblName = "Customers"
strFldName = "Age"
strValidRule = ">= 65"
strValidText = "Enter a number greater than or equal to 65."
intX = SetFieldValidation(strTblName, strFldName, _

strValidRule, strValidText)

Function SetFieldValidation(strTblName As String, strFldName As String, strValidRule As String, strValidText As String) As Integer

Dim db As Database, td As TableDef, fld As Field
Set db = CurrentDb
Set td = db.TableDefs(strTblName)
Set fld = td.Fields(strFldName)
fld.ValidationRule = strValidRule
fld.ValidationText = strValidText
End Function

The next example uses the SetTableValidation function to set record level validation to ensure that the value in the EndDate field comes after the value in the StartDate field.

Dim strTblName As String, strValidRule As String

Dim strValidText As String

Dim intX As Integer
strTblName = "Employees"
strValidRule = "EndDate > StartDate"
strValidText = "Enter an EndDate that is later than the StartDate."
intX = SetTableValidation(strTblName, strValidRule, strValidText)

Function SetTableValidation(strTblName As String, strValidRule As String, strValidText As String) As Integer

Dim db As Database, td As TableDef
Set db = CurrentDb
Set td = db.TableDefs(strTblName)
td.ValidationRule = strValidRule
td.ValidationText = strValidText
End Function


Filter Property (Microsoft Access)

You can use the Filter property to specify a subset of records to be displayed when a filter is applied to a form, query, or table.

Setting

The Filter property is a string expression consisting of a WHERE clause without the WHERE keyword. For example, the following Visual Basic code defines applies a filter to show only customers from the USA:

Me.Filter = "Country = 'USA'"

Me.FilterOn = True

You can set this property in the following ways:

Forms

Table property sheets

Macros

Visual Basic.

You can also set this property in Form view or Datasheet view by pointing to Filter on the Records menu and clicking one of the commands on the submenu.

Note   Setting the Filter property has no affect on the data access Filter property.

Remarks

You can use the Filter property to save a filter and apply it at a later time. Filters are saved with the objects in which they are created. They are automatically loaded when the object is opened, but they aren't automatically applied.

When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn properties of the table or query it was created from. For forms and reports, inherited filters aren't automatically applied when an object is opened.

To apply a saved filter to a form, query, or table, you can click the Apply Filter button on the toolbar, click Apply Filter/Sort on the Records menu, or use a macro or Visual Basic to set the FilterOn property to True (-1). For reports, you can apply a filter by setting the FilterOn property to Yes in the report's property sheet.

The Apply Filter button indicates the state of the Filter and FilterOn properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Filter button appears pressed in.

To apply a filter automatically when a form is opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object.

You can remove a filter by clicking the pressed-in Apply Filter button, clicking Remove Filter/Sort on the Records menu, or using Visual Basic to set the FilterOn property to False (0).

Note   You can save a filter as a query by clicking Save As Query on the File menu while in the Filter By Form window or the Advanced Filter/Sort window.

When the Filter property is set in form Design view, Microsoft Access does not attempt to validate the SQL expression. If the SQL expression is invalid, an error occurs when the filter is applied.


FilterLookup Property

You can use the FilterLookup property to specify whether values appear in a bound text box control when using the Filter By Form window.

Setting

The FilterLookup property uses the following arguments.

Setting	Description	Visual Basic
Never	The field values aren't displayed. You can specify whether the filtered records can contain Null values.	0
Database Default	(Default) The field values are displayed according to the settings in the Filter By Form Defaults section on the Option dialog box's Edit/Find tab, available by clicking Options on the Tools menu.	1
Always	The field values are always displayed.	2
You can set the FilterLookup property in the text box's property sheet, a macro, or using Visual Basic.

You can also set the FilterLookup property for a text box using the control's default control style.

Remarks

If you find that a large list of field values take too long to display, you can limit the number of fields that will be displayed. To do this, clear the appropriate check box in the Filter By Form Defaults section on the Option dialog box's Edit/Find tab, available by clicking Options on the Tools menu. If field lists aren't displaying values correctly, you can increase the number in the Don't Display Lists Where More Than This Number Of Records Read box so the setting is greater than or equal to the maximum number of records in any nonindexed field in the underlying source of records.


FilterOn Property

You can use the FilterOn property to specify or determine whether the Filter property for a form or report is applied.

Setting

The FilterOn property uses the following arguments.

Setting	Description	Visual Basic
Yes	The object's Filter property is applied.	True (-1)
No	(Default) The object's Filter property isn't applied.	False (0)
For reports, you can set the FilterOn property in the report's property sheet or using Visual Basic.

For forms, you can set the FilterOn property using a macro or Visual Basic. You can also set this property by clicking the Apply Filter button on the Form view toolbar or the Filter/Sort toolbar.

Remarks

To apply a saved filter, press the Apply Filter button for forms, or apply the filter using a macro or Visual Basic by setting the FilterOn property to True (-1) for forms or reports. For reports, you can set the FilterOn property to Yes in the report's property sheet.

The Apply Filter button indicates the state of the Filter and FilterOn properties. The button remains disabled until there is a filter to apply. If an existing filter is currently applied, the Apply Filter button appears pressed in. To apply a filter automatically when a form or report is opened, specify in the OnOpen event property setting of the form either a macro that uses the ApplyFilter action or an event procedure that uses the ApplyFilter method of the DoCmd object.

You can remove a filter by clicking the pressed-in Apply Filter button, clicking Remove Filter/Sort on the Records menu, or using Visual Basic to set the FilterOn property to False (0). For reports, you can remove a filter by setting the FilterOn property to No in the report's property sheet.

Note   When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn properties of the table or query it was created from. For forms and reports, inherited filters aren't automatically applied when an object is opened.


OrderBy Property

You can use the OrderBy property to specify how you want to sort records in a form, query, report, or table.

Setting

The OrderBy property is a string expression that is the name of the field or fields on which you want to sort records. When you use more than one field name, separate the names with a comma (,).

When you set the OrderBy property by entering one or more field names, the records will be sorted in ascending order. Similarly, Visual Basic will sort these fields in ascending order by default.

If you want to sort records in descending order, type DESC at the end of the string expression. For example, to sort customer records in descending order by contact name, set the OrderBy property to "ContactName DESC".

You can set the OrderBy property in the object's property sheet, a macro, or using Visual Basic.

Remarks

For reports, the OrderByOn property must be set to Yes to apply the sort order specified by the object's OrderBy property. For forms, select the field on which you want to order the records and either click the appropriate Sort button on the toolbar, or point to Sort on the Records menu and click the appropriate command on the submenu. You can also set the OrderByOn property for either forms or reports using Visual Basic.

Note   When a new object is created, it inherits the RecordSource, Filter, OrderBy, and OrderByOn properties of the table or query it was created from. For forms and reports, inherited filters aren't automatically applied an object is opened.


OrderByOn Property

You can use the OrderByOn property to specify whether an object's OrderBy property setting is applied.

Setting

The OrderByOn property uses the following arguments.

Setting	Description	Visual Basic
Yes	(Default) The OrderBy property setting is applied when the object is opened.	True (-1)
No	The OrderBy property setting isn't applied when the object is opened.	False (0)
For reports, you can set the OrderByOn property in the report's property sheet, a macro, or using Visual Basic.

For all other objects, you can set the OrderByOn property by clicking the sort button from the toolbar or using Visual Basic.

Remarks

When a new object is created, it inherits the RecordSource, Filter, OrderBy, OrderByOn, and FilterOn properties of the table or query it was created from.


ObjectPalette Property

You can use the ObjectPalette property with the PaintPalette property to specify which palette is used by the application to create:

An OLE object contained in a bound object frame, chart, or unbound object frame.

A bitmap that is loaded into a command button or a toggle button using the Picture property.

Setting

Microsoft Access uses a String data type in the ObjectPalette property to set the value of the PaintPalette property for a form or report.

For the following objects, views, and controls, the Object Palette property setting is read-only.

Object	View	Control
Forms	Design view and Form view	Command button, chart, toggle button, and unbound object frame
	Form view	Bound object frame
Reports	Design view	Command button, chart, toggle button, and unbound object frame
You can use this property only in a macro or Visual Basic.

Remarks

The setting of the ObjectPalette property makes the palette of the application associated with the OLE object available to the PaintPalette property of a form or report. For example, to make the palette used in Microsoft Graph available when you're designing a form in Microsoft Access, you set the form's PaintPalette property to the ObjectPalette value of an existing chart control.

Note   Windows can have only one color palette active at a time. Microsoft Access allows you to have multiple graphics on a form, each using a different color palette. The PaletteSource property lets you specify which color palette a form should use when displaying graphics.


ObjectPalette, PaintPalette Properties Example

The following example sets the PaintPalette property of the Seascape form to the ObjectPalette property of the Ocean control on the DisplayPictures form. (Ocean can be a bound object frame, command button, chart, toggle button, or unbound object frame.)

Forms![Seascape].PaintPalette = Forms![DisplayPictures]![Ocean].ObjectPalette

The ObjectPalette and PaintPalette properties are useful for programmatically altering the color palette in use by an open form at run time. A common use of these properties is to set the current form PaintPalette property to that of a graphic displayed in a control that has the focus.

For example, you can have a form with an ocean picture, showing many shades of blue, and a sunset picture, showing many shades of red. Since Windows only allows one color palette active at a time, one picture will look much better than the other. The following example uses a control's Enter event for setting the form's PaintPalette property to the control's ObjectPalette property so the graphic that has the focus will have an optimal appearance.

Sub OceanPicture_Enter()

Me.PaintPalette = Me![OceanPicture].ObjectPalette

End Sub

Sub SunsetPicture_Enter()

Me.PaintPalette = Me![SunsetPicture].ObjectPalette

End Sub


PaintPalette Property

You can use the PaintPalette property to specify a palette that can be used by the PaletteSource property of a form or report.

Setting

You can set the PaintPalette property using a macro or Visual Basic. The property setting must be a String data type.

For a form, you can set the PaintPalette property in Design view and Form view.

For a report, you can set the PaintPalette property in Design view only.

Remarks

When you set the PaintPalette property, Microsoft Access makes a copy of the palette that you specify and saves it with the form or report. The palette is then available if you modify that form or report.

Changes to the palette you specified when you set the PaintPalette property don't affect the copy of the palette stored with the form or report. If you want to update the copy of the palette stored with the form or report, you must rerun the code or macro that sets the PaintPalette property or reset the PaletteSource property when the form or report is open.

When you set the PaintPalette property for a form or report, Microsoft Access automatically updates its PaletteSource property. Conversely, when you set the PaletteSource property for a form or report, the PaintPalette property is also updated. For example, when you specify a custom palette with the PaintPalette property, the PaletteSource property setting is changed to Custom.

Note   Windows can have only one color palette active at a time. Microsoft Access allows you to have multiple graphics on a form, each using a different color palette. The PaletteSource property lets you specify which color palette a form should use when displaying graphics.


PaletteSource Property

You can use the PaletteSource property to specify the palette for a form or report.

Setting

Enter the path and filename of one of the following file types:

.dib (device independent bitmap file)

.pal (Windows palette file)

.ico (Windows icon file)

.bmp (Windows bitmap file)

The default setting is (Default), which specifies the palette included with Microsoft Access. If you change this setting by entering a path and filename, the property setting displays the word Custom.

You can set this property using the property sheet, a macro, or Visual Basic.

For a form, you can set the PaletteSource property in Design view and Form view.

For a report, you can set the PaletteSource property only in Design view.

Remarks

Windows can have only one color palette active at a time. Microsoft Access allows you to have multiple graphics on a form, each using a different color palette. The PaletteSource property lets you specify which color palette a form uses when displaying graphics.

When you set the PaletteSource property for a form or report, Microsoft Access automatically updates its PaintPalette property. Conversely, when you set a form's or report's PaintPalette property, the PaletteSource property is also updated. For example, when you specify a custom palette with the PaintPalette property, the PaletteSource property setting changes to Custom.


PopUp Property

You can use the PopUp property to specify whether a form opens as a pop-up. For example, you set a form's PopUp and Modal properties to Yes to create a custom dialog box.

Setting

The PopUp property uses the following settings.

Setting	Description	Visual Basic
Yes	The form opens as a pop-up form in Form view. It remains on top of all other Microsoft Access windows.	True (-1)
No	(Default) The form is not a pop-up form.	False (0)
You can set this property using the form's property sheet, a macro, or Visual Basic.

The PopUp property can be set only in Design view.

Remarks

To specify the type of border you want on a pop-up form, use the BorderStyle property. You typically set the BorderStyle property to Thin for pop-up forms.

Tip   You can use the PopUp, Modal and BorderStyle properties to create a custom dialog box. Set Modal to Yes, PopUp to Yes and BorderStyle to Dialog for custom dialog boxes.

Setting the PopUp property to Yes makes the form a pop-up only when you open it in Form view from the Database window or when using a macro or Visual Basic. When the PopUp property is set to Yes, you can't switch to other views from Form view. You must close the form and reopen it in Design view or Datasheet view.

Note   You can use the Dialog setting of the Window Mode argument of the OpenForm action to open a form with its PopUp and Modal properties set to Yes.


ShortcutMenu Property

You can use the ShortcutMenu property to specify whether a shortcut menu is displayed when you click the right mouse button while the pointer is over an object on a form. You might want to disable a shortcut menu to prevent the user from changing the form's underlying record source.

Setting

The ShortcutMenu property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) Shortcut menus are displayed.	True (-1)
No	Shortcut menus aren't displayed.	False (0)
You can set this property using the form's property sheet, a macro, or Visual Basic.

Remarks

If you're developing a wizard, you might want to hide shortcut menus on your wizard forms to prevent the user from viewing or using them. This is especially true for forms that display choices. For example, the ShortcutMenu property for the Startup form in the Northwind sample database is set to No. This prevents users from displaying shortcut menus for the form or controls on the form.


ShortcutMenu Property Example

The following example disables the shortcut menu for the Invoice form.

Forms![Invoice].ShortcutMenu = False


TabIndex Property

You can use the TabIndex property to specify a control's place in the tab order on a form.

Note   The TabIndex property applies only to controls on a form.

Setting

You can set the TabIndex property to an integer representing the position of the control within the tab order of the form. Valid settings are 0 for the first tab position, up to the total number of controls minus 1 for the last tab position. For example, if a form has three controls that each have a TabIndex property, valid TabIndex property settings are 0, 1, and 2.

Setting the TabIndex property to an integer less than 0 produces an error.

You can set this property using the control's property sheet, a macro, or Visual Basic.

Remarks

By default, Microsoft Access assigns a tab order to controls in the order that you create them on a form. Each new control is placed last in the tab order. If you change the setting of a control's TabIndex property to adjust the tab order, Microsoft Access automatically renumbers the TabIndex property setting of other controls to reflect insertions and deletions.

In Form view, invisible or disabled controls remain in the tab order but are skipped when you press the TAB key.

Changing the tab order of other controls on the form doesn't affect what happens when you press a control's access key. For example, if you've created an access key for the label of a text box, the focus will move to the text box whenever you press the label's access key [image] even if you change the TabIndex property setting for the text box.

If you press an access key for a control that doesn't have a TabIndex property, the focus moves to the next control in the tab order that can receive the focus.


TabIndex Property Example

The following example reverses the tab order of a command button and a text box. Because Textbox1 was created first, it has a TabIndex property setting of 0 and Command1 has a setting of 1.

Sub Form_Click()

Me![Command1].TabIndex = 0

Me![TextBox1].TabIndex = 1

End Sub


TabStop Property

You can use the TabStop property to specify whether a control can receive the focus in Form view.

Note   The TabStop property applies only to controls on a form.

This property doesn't apply to check box, option button, or toggle button controls when they appear in an option group. It does apply only to the option group itself.

Setting

The TabStop property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) You can move the focus to the control by pressing the TAB key.	True (-1)
No	You can't move the focus to the control by pressing the TAB key.	False (0)
You can set this property using the control's property sheet, a macro, or Visual Basic.

Remarks

When you create a control on a form, Microsoft Access automatically assigns the control a position in the form's tab order. Each new control is placed last in the tab order. If you want to prevent a control from being available when you tab through the controls in a form, set the control's TabStop property to No.

In Form view, hidden or disabled controls remain in the tab order but are skipped when you tab through the controls, even if their TabStop properties are set to Yes.

As long as a control's Enabled property is set to Yes, you can click it or use an access key to select it, regardless of its TabStop property setting. For example, you can set the TabStop property of a command button to No to prevent users from selecting the button by pressing the TAB key. However, they can still click the command button to choose it.


Tag Property

You can use the Tag property to store any extra information about a form, report, section, or control needed by your application.

Setting

You can enter a string expression up to 2048 characters long. The default setting is a zero-length string (" ").

You can set this property using the object's property sheet, a macro, or Visual Basic.

Remarks

Unlike other properties, the Tag property setting doesn't affect any of an object's attributes.

You can use this property to assign an identification string to an object without affecting any of its other property settings or causing other side effects. The Tag property is useful when you need to check the identity of a form, report, section, or control that is passed as a variable to a procedure.


Tag Property Example

The following example uses the Tag property to display custom messages about controls on a form. When a control has the focus, descriptive text is displayed in a label control called lblMessage. You specify the text for the message by setting the Tag property for each control to a short text string. When a control receives the focus, its Tag property is assigned to the label control's Caption property.

Sub Form_Load()

Dim frmMessageForm As Form

Set frmMessageForm = Forms!Form1

frmMessageForm!lblMessage.Caption = ""	 ' Clear text.

frmMessageForm!txtDescription.Tag = "Help text for the text box."

frmMessageForm!cmdButton.Tag = "Help text for the command button."

End Sub

Sub txtDescription_GotFocus()

Me!lblMessage.Caption = Me!txtDescription.Tag	 ' Tag property as caption.

End Sub

Sub txtDescription_LostFocus()

Me!lblMessage.Caption = ""

End Sub

Sub cmdButton_GotFocus()

Me!lblMessage.Caption = Me!cmdButton.Tag	 ' Tag property as caption.

End Sub

Sub cmdButton_LostFocus()

Me.lblMessage.Caption = " "

End Sub


AllowAdditions Property

You can use the AllowAdditions property to specify whether a user can add a record using a form.

Setting

The AllowAdditions property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The user can add new records.	True (-1)
No	The user can't add new records	False (0)
You can set the AllowAdditions property in the form's property sheet, a macro, or using Visual Basic.

Remarks

Set the AllowAdditions property to No to allow users to view or edit existing records but not add new records.

If you want to prevent changes to existing records (make a form read-only), set the AllowAdditions, AllowDeletions, and AllowEdits properties to No. You can also make records read-only by setting the RecordsetType property to Snapshot.

If you want to open a form for data entry only, set the form's DataEntry property to Yes.

When AllowAdditions is set to No, the Data Entry command on the Records menu is not available.


AllowAutoCorrect Property

You can use the AllowAutoCorrect property to specify whether a text box or a combo box control will automatically correct entries made by the user.

Setting

The AllowAutoCorrect property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) Entries are automatically corrected according to the settings in the AutoCorrect dialog box.	True (-1)
No	Entries are not corrected.	False (0)
You can set the AllowAutoCorrect property in a control's property sheet, a macro, or using Visual Basic. You can also set this property in the control's default control style.

Remarks

The AutoCorrect dialog box is available by clicking AutoCorrect on the Tools menu.


AllowDeletions Property

You can use the AllowDeletions property to specify whether a user can delete a record using a form.

Setting

The AllowDeletions property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The user can delete records.	True (-1)
No	The user can't delete records.	False (0)
You can set the AllowDeletions property in the form's property sheet, a macro, or using Visual Basic.

Remarks

You can set this property to No to allow users to view and edit existing records but not to delete them. When AllowDeletions is set to Yes, records may be deleted so long as existing referential integrity rules are not violated.

If you want to prevent changes to existing records (make a form read-only), set the AllowAdditions, AllowDeletions, and AllowEdits properties to No. You can also make records read-only by setting the RecordsetType property to Snapshot.

When AllowDeletions is set to No, the Delete Record command on the Edit menu is not available.


AllowEdits Property

You can use the AllowEdits property to specify whether a user can edit saved records using a form.

Setting

The AllowEdits property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The user can edit saved records.	True (-1)
No	The user can't edit saved records.	False (0)
You can set the AllowEdits property in the form's property sheet, a macro, or using Visual Basic.

Remarks

You can use the AllowEdits property to prevent changes to all data displayed by a form. If you want to prevent changes to data in a specific control, use the Enabled or Locked properties.

If you want to prevent changes to existing records (make a form read-only), set the AllowAdditions, AllowDeletions, and AllowEdits properties to No. You can also make records read-only by setting the RecordsetType property to Snapshot.


CloseButton Property

You can use the CloseButton property to specify whether the Close button on a form is enabled.

Setting

The CloseButton property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The Close button is enabled.	True (-1)
No	The Close button is disabled and the Close command isn't available on the Control menu.	False (0)
You can set the CloseButton property in the form or report's property sheet, a macro, or using Visual Basic.

You can set the CloseButton property only in form Design view.

Remarks

If you set the CloseButton property to No, the Close button remains visible but is dimmed, and you must provide some other way to close the form — for example, a command button or custom menu command that runs a macro or event procedure that closes the form.


ControlType Property

You can use the ControlType property in Visual Basic to determine the type of a control on a form.

Note   The ControlType property applies only to controls on a form.

Setting

The ControlType property setting is a constant corresponding to an Integer value that specifies the control type.

Constant	Value	Control
acLabel	100	Label
acRectangle	101	Rectangle
acLine	102	Line
acImage	103	Image
acCommandButton	104	Command button
acOptionButton	105	Option button
acCheckBox	106	Check box
acOptionGroup	107	Option group
acBoundObjectFrame	108	Bound object frame
acTextBox	109	Text box
acListBox	110	List box
acComboBox	111	Combo box
acSubform	112	Subform
acObjectFrame	114	Unbound object frame
acPageBreak	118	Page break
acCustomControl	119	Custom control
acToggleButton	122	Toggle button
The ControlType property can only be set using Visual Basic in form Design view but can be read in all views.

Remarks

The ControlType property is useful not only for checking for a specific control type in code, but also for changing the type of control to another type. For example, you can change a text box to a combo box by setting the ControlType property for the text box to acComboBox while in form Design view.

You can use the ControlType property to change characteristics of similar controls on a form according to certain conditions. For example, if you don't want certain users to edit existing data in text boxes, you can set the SpecialEffect property for all text boxes to Flat and set the form's AllowEdits property to No. The SpecialEffect property does not affect whether data can be edited; it is used here to provide a visual clue that the control behavior has changed.

The ControlType property is also used to specify the type of control to create using the CreateControl function.


ControlType, AllowAdditions, AllowDeletions, AllowEdits Properties Example

The following example examines the ControlType property for all controls on a form. For each label and text box control, the procedure toggles the SpecialEffect property for those controls. When the label controls' SpecialEffect property is set to Shadowed and the Text box controls' SpecialEffect property is set to Normal and the AllowAdditions, AllowDeletions, and AllowEdits properties are all set to True.

Sub ToggleControl(frm As Form)

Dim ctlCurrentControl As Control

Dim intI As Integer, intCanEdit As Integer

Const conTransparent = 0

Const conWhite = 16777215

For intI = 0 To frm.Count - 1

Set ctlCurrentControl = frm(intI)

Select Case ctlCurrentControl.ControlType

Case acLabel

If ctlCurrentControl.SpecialEffect = acEffectShadow Then

ctlCurrentControl.SpecialEffect = acEffectNormal

ctlCurrentControl.BorderStyle = conTransparent

intCanEdit = True

Else

ctlCurrentControl.SpecialEffect = acEffectShadow

intCanEdit = False

End If

Case acTextBox

If ctlCurrentControl.SpecialEffect = acEffectNormal Then

ctlCurrentControl.SpecialEffect = acEffectSunken

ctlCurrentControl.BackColor = conWhite

Else

ctlCurrentControl.SpecialEffect = acEffectNormal

ctlCurrentControl.BackColor = frm.Detail.BackColor

End If

End Select

Next intI

If intCanEdit = False Then

frm.AllowAdditions = False

frm.AllowDeletions = False

frm.AllowEdits = False

Else

frm.AllowAdditions = True

frm.AllowDeletions = True

frm.AllowEdits = True

End If

End Sub


DataEntry Property

You can use the DataEntry property to specify whether a bound form opens to allow data entry only.

Setting

The DataEntry property uses the following settings.

Setting	Description	Visual Basic
Yes	The form opens showing only a blank record.	True (-1)
No	(Default) The form opens showing existing records.	False (0)
You can set the DataEntry property in a form's property sheet, a macro, or using Visual Basic.

This property can be set in any view.

Remarks

The DataEntry property is effective only when a form has a valid RecordSource property setting and the AllowAdditions property is set to Yes.

Setting the DataEntry property to Yes using Visual Basic has the same effect as clicking Data Entry on the Records menu. Setting it to No using Visual Basic is equivalent to clicking Remove Filter/Sort on the Records menu.


MultiSelect Property

You can use the MultiSelect property to specify whether a user can make multiple selections in a list box and how the multiple selections can be made.

Setting

The MultiSelect property uses the following settings.

Setting	Description	Visual Basic
None	(Default) Multiple selection isn't allowed.	0
Simple	Multiple items are selected or deselected by choosing them with the mouse or pressing the spacebar.	1
Extended	Multiple items are selected by pressing SHIFT+CLICK or SHIFT+ARROW to extend the selection from the previously selected item to the current item. Holding down CTRL and clicking an item selects or deselects that item.	2
You can set the MultiSelect property in the list box's property sheet, a macro, or using Visual Basic. You can also set this property in a list box's default control style.

This property can be set in any view.

Remarks

You can use the ListIndex property to return the index for the selected item. When the MultiSelect property is set to Extended or Simple, you can use the list box's Selected property or ItemsSelected collection to determine the items that are selected.


DividingLines Property

You can use the DividingLines property to specify whether dividing lines will separate sections on a form or records displayed on a continuous form.

Setting

The DividingLines property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) Dividing lines will separate sections and records on continuous forms.	True (-1)
No	There are no dividing lines.	False (0)
You can set the DividingLines property in the form's property sheet, a macro, or using Visual Basic.

This property can be set in any view.


Selected Property

You can use the Selected property in Visual Basic to determine if an item in a list box is selected.

Setting

The Selected property is a zero based array of all the items in a list box that contains the selected state of each item in the list.

Setting	Description

True (-1)	The list box item is selected.

False (0)	The list box item isn't selected.

You can get or set the Selected property using Visual Basic.

This property is available only at run time.

Remarks

When a list box control's MultiSelect property is set to None, only one item can have its Selected property set to True. When a list box control's MultiSelect Property is set to Simple or Extended, any or all of the items can have their Selected property set to True.

You can use the Selected property to select items in a list box using Visual Basic. For example, the following expression selects the fifth item in the list.

Me!Listbox.Selected(4) = True


Selected Property Example

The following example uses the Selected property to move selected items in the lstSource list box to the lstDestination list box. The lstDestination list box's RowSourceType property is set to Value List and the control's RowSource property is constructed from all the selected items in the lstSource control. The lstSource list box's MultiSelect property is set to Extended. The CopySelected( ) function is called from the cmdCopyItems command button.

Sub cmdCopyItem_Click()

CopySelected Me

End Sub

Function CopySelected(frm As Form) As Integer

Dim ctlSource As Control

Dim ctlDest As Control

Dim strItems As String

Dim intCurrentRow As Integer

Set ctlSource = frm!lstSource

Set ctlDest = frm!lstDestination

For intCurrentRow = 0 To ctlSource.Listcount - 1

If ctlSource.Selected(intCurrentRow) = True Then

strItems = strItems & ctlSource.Column(0, intCurrentRow) & ";"

End If

Next intCurrentRow

' Reset destination control's RowSource

ctlDest.RowSource = ""

ctlDest.RowSource = strItems

End Function


TripleState Property

You can use the TripleState property to specify how a check box, toggle button, or option button will display Null values.

Note   The TripleState property does not apply to the specified controls when they are used inside of an option group control.

Setting

The TripleState property uses the following settings.

Setting	Description	Visual Basic
Yes	The control will cycle through states for Yes, No, and Null values.	True (-1)
No	(Default) The control will cycle through states for Yes and No values. Null values display like No values.	False (0)
You can set the TripleState property in a control's property sheet, a macro, or using Visual Basic. You can also set this property in the control's default control style.

This property can be set in any view.

Remarks

When the TripleState property of a control is set to Yes, the control appears dimmed when its Value property is set to Null.


DateGrouping Property

You can use the DateGrouping property to specify how you want to group dates in a report. For example, if your country's First Weekday setting is Monday, using the US Defaults setting will cause the week to begin on the incorrect day; if you set a Date/Time field's GroupOn property to Week, the report will group dates from Sunday to Sunday instead of from Monday to Monday.

Note   The DateGrouping property setting applies to the entire report, not to a particular group in the report.

Setting

The DateGrouping property uses the following settings.

Setting	Description	Visual Basic
US Defaults	Microsoft Access uses the default U.S. settings for First Weekday (Sunday) and First Week (starts on Jan 1).	0
Use System Settings	(Default) Microsoft Access uses settings based on the locale selected in the Regional Settings section of the Windows Control Panel.	1
You can set this property in the report's property sheet, a macro, or Visual Basic.

You can set the DateGrouping property only in report Design view or in the Open event procedure of a report.

Remarks

The sort order used in a report isn't affected by the DateGrouping property setting.


DateGrouping Property Example

The following example gets the value of the DateGrouping property for a report and assigns it to the intGetDateGrouping variable.

Dim intGetDateGrouping As Integer

intGetDateGrouping = Reports![LastYear].DateGrouping


GroupHeader, GroupFooter Properties

You can use the GroupHeader and GroupFooter properties to create a group header or a group footer for a selected field or expression. You can use group headers and footers to label groups or summarize data in a group. For example, you can have a Beverages group header that identifies the group of records for beverage products.

Setting

The GroupHeader and GroupFooter properties use the following settings.

Setting	Description

Yes	Creates a group header or footer.

No	(Default) Doesn't create a group header or footer.

You set these properties in the Sorting And Grouping box, available by clicking Sorting And Grouping on the View Menu or by clicking the Sorting And Grouping button on the toolbar.

You can set them only in report Design view.

Note   You can't set or refer to these properties directly in Visual Basic. To create a group header or footer for a field or expression in Visual Basic, use the CreateGroupLevel function.

Remarks

To set the Group properties [image] GroupOn, GroupInterval, and KeepTogether [image] to other than their default values, you must first set the GroupHeader or GroupFooter property to Yes for the selected field or expression.


GroupInterval Property

You can use the GroupInterval property with the GroupOn property to specify how data is grouped in reports. The GroupInterval property specifies an interval value that data is grouped by. This interval differs depending on the data type and GroupOn property setting of the values in the field or expression you're grouping on. For example, you can set the GroupInterval property to 1 if you want to group records by the first character of a product name.

Setting

The GroupInterval property settings are Integer values that depend on the field's data type and its GroupOn property setting. The default GroupInterval setting is 1.

You can set this property in the report's Sorting And Grouping box, a macro, or Visual Basic.

You can set the GroupInterval property only in report Design view or in the Open event procedure of a report.

Remarks

Here are examples of GroupInterval property settings for different field data types.

Field data type	GroupOn setting	GroupInterval setting
All	Each Value	(Default) Automatically set to 1.
Text	Prefix Characters	Set to 3 for grouping by the first three characters in the field (for example, Chai, Chartreuse, and Chang would be grouped together).
Date/Time	Week	Set to 2 to return data in biweekly groups.
Date/Time	Hour	Set to 12 to return data in half-day groups.
To set the GroupInterval property to a value other than its default setting (1), you must first set the GroupHeader or GroupFooter property or both to Yes for the selected field or expression.


GroupLevel Property

You can use the GroupLevel property in Visual Basic to refer to the group level you are grouping or sorting on.

Setting

The GroupLevel property setting is an array in which each entry identifies a group level. To refer to a group level, use this syntax:

GroupLevel(n)

The number n is the group level, starting with 0. The first field or expression you group on is group level 0, the second is group level 1, and so on. You can have up to 10 group levels (0 to 9).

The following sample settings show how you use the GroupLevel property to refer to a group level.

Group Level	Refers to

GroupLevel(0)	The first field or expression you sort or group on.

GroupLevel(1)	The second field or expression you sort or group on.

GroupLevel(2)	The third field or expression you sort or group on.

You can use this property in Visual Basic only to set the SortOrder, GroupOn, GroupInterval, KeepTogether, and ControlSource properties. You set these properties in the Open event procedure of a report.

Remarks

In reports, you can group or sort on more than one field or expression. Each field or expression you group or sort on is a group level.

You specify the fields and expressions to sort and group on using the CreateGroupLevel function.

If group level 0 is already defined for a report, you can use the ControlSource property to reset the group level during the report's Open event procedure. For example, during the Open event procedure of a report, you can display a dialog box called SortForm that prompts you to enter the field to sort on. If you enter a name into a text box (txtPromptYou) in the dialog box, you can set the property to the contents of the text box.

Dim strGetSortField As String

strGetSortField = Forms![SortForm]![txtPromptYou]

Me.GroupLevel(0).ControlSource = strGetSortField


Group Properties Example

The following example sets the sort order and group properties for the first group level in the Products By Category report.

Sub Report_Open()

' Set SortOrder property to descending order.
Reports![Products by Category].GroupLevel(0).SortOrder = True

' Set GroupOn property to Prefix Characters.
Reports![Products by Category].GroupLevel(0).GroupOn = 1

' Set GroupInterval property to 1.
Reports![Products by Category].GroupLevel(0).GroupInterval = 1

' Set KeepTogether property to With First Detail.
Reports![Products by Category].GroupLevel(0).KeepTogether = 2

End Sub


GroupOn Property

You can use the GroupOn property to specify how to group data in a field or expression by data type. For example, this property lets you group a Date field by Month.

Setting

The GroupOn property settings available for a field depend on its data type, as the following table shows. For an expression, all of the settings are available. The default setting for all data types is Each Value.

Field data type	Setting	Groups records with	Visual Basic
Text	(Default) Each Value	The same value in the field or expression.	0
	Prefix Characters	The same first n number of characters in the field or expression.	1
Date/Time	(Default) Each Value	The same value in the field or expression.	0
	Year	Dates in the same calendar year.	2
	Qtr	Dates in the same calendar quarter.	3
	Month	Dates in the same month.	4
	Week	Dates in the same week.	5
	Day	Dates on the same date.	6
	Hour	Times in the same hour.	7
	Minute	Times in the same minute.	8
AutoNumber, Currency, Number	(Default) Each Value	The same value in the field or expression.	0
	Interval	Values within an interval you specify.	9
You can set the GroupOn property in the Sorting And Grouping box, a macro, or Visual Basic.

Using Visual Basic, you set this property in the Open event procedure of a report.

Remarks

To set the GroupOn property to a value other than Each Value, you must first set the GroupHeader or GroupFooter property or both to Yes for the selected field or expression.


KeepTogether Property - Groups
KeepTogether Property — Groups

You can use the KeepTogether property in reports to keep parts of a group [image] including the group header, detail section, and group footer [image] together on the same page. For example, you might want a group header always to be printed on the same page with the first detail section.

Setting

The KeepTogether property uses the following settings.

Setting	Description	Visual Basic
No	(Default) Prints the group without keeping the group header, detail section, and group footer on the same page.	0
Whole Group	Prints the group header, detail section, and group footer on the same page.	1
With First Detail	Prints the group header on a page only if it can also print the first detail record.	2
You can set the KeepTogether property in a report's Sorting And Grouping box, a macro, or Visual Basic.

In Visual Basic, you set the KeepTogether property in Design view or the Open event procedure of a report using the GroupLevel property.

Remarks

To set the KeepTogether property to a value other than No, you must set the GroupHeader or GroupFooter property to Yes for the selected field or expression.

A group includes the group header, detail section, and group footer. If you set the KeepTogether property to Whole Group and a group is too large to fit on one page, Microsoft Access will ignore the setting for that group. Similarly, if you choose With First Detail and either the group header or detail record is too large to fit on one page, the setting will be ignored.


SortOrder Property

You use the SortOrder property to specify the sort order for fields and expressions in a report. By specifying a sort order, you can organize your records in a particular order. For example, if you're printing a list of suppliers, you can sort the records alphabetically by company name.

Setting

The SortOrder property uses the following settings.

Setting	Description	Visual Basic
Ascending	(Default) Sorts values in ascending (A to Z, 0 to 9) order	False (0)
Descending	Sorts values in descending (Z to A, 9 to 0) order	True (-1)
You can set the SortOrder property in the Sorting And Grouping box of a report, a macro, or Visual Basic.

In Visual Basic, you set the SortOrder property in report Design view or the Open event procedure of a report using the GroupLevel property.


EventProcPrefix Property

You can use the EventProcPrefix property to get the prefix portion of an event procedure name. For example, if you have a command button with an event procedure named Details_Click, the EventProcPrefix property returns the string "Details".

Setting

The EventProcPrefix property setting is a string expression.

This property is available only in a macro or Visual Basic and is read-only in all views.

Remarks

Microsoft Access appends the prefix portion of an event procedure name to the event name with an underscore character (_).


TimerInterval Property

You can use the TimerInterval property in to specify the interval, in milliseconds, between Timer events on a form.

Setting

The TimerInterval property setting is a Long Integer between 0 and 2,147,483,647 representing the interval, in milliseconds, between Timer events on a form.

You can set this property using the form's property sheet, a macro, or Visual Basic.

When using Visual Basic, you set the TimerInterval property in the form's Load event.

Remarks

Put Visual Basic code you want run at intervals specified by the TimerInterval property in the Timer event procedure for a form. For example, to requery records every 30 seconds, you can put code in the Timer event procedure for a form to requery the records, and then set the TimerInterval property to 30000.


TimerInterval Property Example

The following example shows how to create a flashing button on a form by displaying and hiding an icon on the button. The form's Load event procedure sets the form's TimerInterval property to 1000 so the icon display is toggled once every second.

Sub Form_Load()

Me.TimerInterval = 1000

End Sub

Sub Form_Timer()

Static intShowPicture As Integer

If intShowPicture Then

Me!btnPicture.Picture = "C:\Icons\Flash.ico"

Else

Me!btnPicture.Picture = Null	' Don't show icon.

End If

intShowPicture = Not intShowPicture

End Sub


AutoRepeat Property

You can use the AutoRepeat property to specify whether an event procedure or macro runs repeatedly while a command button on a form remains pressed.

Setting

The AutoRepeat property uses the following settings.

Setting	Description	Visual Basic
Yes	The macro or event procedure in the Click event runs repeatedly while the command button remains pressed.	True (-1)
No	(Default) The macro or event procedure runs once.	False (0)
You can set this property using the property sheet, a macro, or Visual Basic.

Remarks

The initial repeat of the event procedure or macro occurs 0.5 second after it first runs. Subsequent repeats occur either 0.25 second apart or the duration of the event procedure or macro, whichever is longer.


Count Property (Microsoft Access)

You can use the Count property to determine the number of open forms or reports, or the number of controls on an open form or report.

Setting

The Count property setting is an Integer and is read-only in all views.

You can determine the Count property using a macro or Visual Basic.

If no forms or reports are open, the Count property setting is 0.


Count Property Example

The following example uses the Count property to control a loop that prints information about all open forms.

Sub Print_Form_Controls()

Dim frm As Form, intI As Integer, intJ As Integer, strTab As String

Dim intControls As Integer, intForms As Integer

strTab = Chr(9)	' Tab character.

intForms = Forms.Count	' Number of open forms.

If intForms > 0 Then

For intI = 0 To intForms - 1

Set frm = Forms(intI)

Debug.Print frm.Name	' Print form name.

intControls = frm.Count

If intControls > 0 Then

For intJ = 0 To intControls - 1

Debug.Print strTab; frm(intJ).Name	' Print control name.

Next intJ

Else

Debug.Print strTab; "(no controls)"

End If

Next intI

Else

MsgBox "No open forms.", vbExclamation, "Form Controls"

End If

End Sub

The next example determines the number of controls on a form or report and assigns this number to a variable.

Dim intFormControls As Integer

Dim intReportControls As Integer

intFormControls = Forms![Employees].Count

intReportControls = Reports![FreightCharges].Count


CurrentView Property

You can use the CurrentView property to determine how a form is currently displayed. For example, you might need to know whether a form is in Form view or Datasheet view before you attempt to place controls on the form using Visual Basic.

Settings

The CurrentView property uses the following settings.

Setting	Description

0	The form is displayed in Design view.

1	The form is displayed in Form view.

2	The form is displayed in Datasheet view.

This property is available only in a macro or Visual Basic and is read-only in all views.

Remarks

You can also use this property to perform different tasks depending on the view. For example, a menu command running code can determine which view the form is displayed in and perform one task if the form is displayed in Form view or another task if it's displayed in Datasheet view.


CurrentView Property Example

The following example determines whether a form is in Form or Datasheet view. If it's in Form view, a message is displayed in a text box on the form; if it's in Datasheet view, the same message is displayed in a message box.

Function GetCurrentView(frm As Form, strDisplayMsg As String)

Const conFormView = 1

Const conDataSheet = 2

Dim intView As Integer

intView = frm.CurrentView

Select Case intView

Case conFormView

frm!MessageTextBox.SetFocus	' Set focus to text box.

frm!MessageTextBox = strDisplayMsg	' Display message in text box.

Case conDataSheet

MsgBox strDisplayMsg	' Display message in message box.

End Select

End Function


HelpContextID, HelpFile Properties (Microsoft Access)

HelpContextID [image] You can use this property to specify the context ID for a topic in the custom Help file specified by the HelpFile property setting.

HelpFile [image] You can use this property to specify the name of a custom Help file for the current form or report.

Setting

HelpContextID [image] Enter a Long Integer between 0 and 2,147,483,647. The default setting is 0.

HelpFile [image] Enter a string expression that contains the path and filename of a custom Help file created with the Windows Help Compiler.

You can set these properties using the property sheet, a macro, or Visual Basic.

Remarks

You can create a custom Help file to document forms, reports, or applications you create with Microsoft Access.

When you press the F1 key in Form view, Microsoft Access calls the Windows Help application, loads the custom Help file specified by the HelpFile property setting for the form or report, and displays the Help topic specified by the HelpContextID property setting.

If a control's HelpContextID property setting is 0 (the default), Microsoft Access uses the form's HelpContextID and HelpFile properties to identify the Help topic to display. If you press F1 in a view other than Form view or if the HelpContextID property setting for both the form and the control is 0, a Microsoft Access Help topic is displayed.

Note   To create a custom Help file, you need the Windows Help Compiler and a rich-text format (RTF) text editor, such as Microsoft Word for Windows.


HelpContextID, HelpFile Properties - Applies To
HelpContextID, HelpFile Properties — Applies To

HelpContextID Property

HelpFile Property


hWnd Property

You can use the hWnd property to determine the handle (a unique Long Integer) assigned by Microsoft Windows to the current window.

Setting

This property is read-only and is available only in a macro or Visual Basic.

Remarks

You can use this property in Visual Basic when making calls to Windows Application Programming Interface (API) functions or other external routines that require the hWnd property as an argument. Many Windows functions require the hWnd property value of the current window as one of the arguments.

Caution   Because the value of this property can change while a program is running, don't store the hWnd property value in a global variable.


hWnd Property Example

The following example uses the hWnd property with the Windows Application Programming Interface (API) IsZoomed function to determine if a window is maximized.

' Enter on single line in Declarations section of Module window.

Declare Function IsZoomed Lib "USER32" (ByVal hWnd As Long) As Integer

Sub Form_Activate()

Dim intWindowHandle As Long

intWindowHandle = Screen.ActiveForm.hWnd

If Not IsZoomed(intWindowHandle) Then

DoCmd.Maximize

End If

End Sub


InSelection Property

You can use the InSelection property to determine or specify whether a control on a form in Design view is selected.

Setting

The InSelection property uses the following settings.

Setting	Description

True (-1)	The control is selected.

False (0)	The control isn't selected.

This property is available only in a macro or Visual Basic.

Remarks

When a control is selected, its sizing handles are visible and it can be resized by the user. More than one control can be selected at a time.


InSelection Property Example

The following example uses the InSelection property to determine whether the strControlName control on a form is selected.

Function IsControlSelected(frm As Form, strControlName As String) As Integer

Dim intI As Integer, ctl As Control

If frm.CurrentView <> 0 Then

' Form is not in Design view.

Exit Function

Else

For intI = 0 To frm.Count-1

Set ctl = frm(intI)

If ctl.InSelection = True Then

' Is desired control selected?

If UCase(ctl.Name) = UCase(strControlName) Then

IsControlSelected = True

End If

Else

IsControlSelected = False

End If

Next intI

End If

End Function


OpenArgs Property

You can use the OpenArgs property to determine the string expression specified by the openargs argument of the OpenForm method that opens a form.

Setting

This property is available only in a macro or Visual Basic using the DoCmd.OpenForm method. This property setting is read-only in all views.

Remarks

To use the OpenArgs property, open a form using the DoCmd.OpenForm method, and set the openargs argument to the desired string expression. The OpenArgs property setting can then be used in code for the form, such as an Open event procedure. You can also refer to the property setting in a macro, such as an Open macro, or an expression, such as an expression that sets the ControlSource property for a control on the form.

For example, suppose that the form you open is a continuous-form list of clients. If you want the focus to move to a specific client record when the form opens, you can set the OpenArgs property to the client name, and then use the FindRecord action in an Open macro to move the focus to the record for the client with the specified name.


OpenArgs Property Example

The following example uses the OpenArgs property to open an Employees form to a specific employee record and demonstrates how the OpenForm action sets the OpenArgs property. You can run this procedure in an appropriate instance [image] for example, when the AfterUpdate event occurs for a custom dialog box used to enter new information on an employee. The Open event procedure for the Employees form uses the OpenArgs property to open the form to the specific employee record.

Sub OpenToCallahan()

DoCmd.OpenForm "Employees", acNormal, , , acReadOnly, , "Callahan"

End Sub

Sub Form_Open(Cancel As Integer)

Dim strEmployeeName As String

' If OpenArgs property contains employee name,

' find corresponding employee record

' and display it on form. For example, if the

' OpenArgs property contains "Callahan",

' move to first "Callahan" record.

strEmployeeName = Forms![Employees].OpenArgs

If Len(strEmployeeName) > 0 Then

DoCmd.GoToControl "LastName"

DoCmd.FindRecord strEmployeeName, ,True, , True, , True

End If

End Sub

The next example uses the FindFirst method to locate the employee named in the OpenArgs property.

Private Sub Form_Open(Cancel As Integer)

If Not IsNull(Me.OpenArgs) Then

Dim strEmployeeName As String

strEmployeeName = Me.OpenArgs

Dim RS As Recordset

Set RS = Me.RecordsetClone

RS.FindFirst "[LastName] = '" & strEmployeeName & "'"

If Not RS.NoMatch Then

Me.Bookmark = RS.Bookmark

End If

End If

End Sub


PreviousControl Property

You can use the PreviousControl property with the Screen object to determine the control that last received the focus.

Setting

The PreviousControl property setting is a String value that is the name of a control.

This property is available only in a macro or Visual Basic and is read-only.

Remarks

You can't use the PreviousControl property until more than one control on any form has received the focus after a form is opened. Microsoft Access generates an error if you attempt to access this property when only one control on a form has received the focus.


PreviousControl Property Example

The following example displays a message if the control that last received the focus was not the txtFinalEntry text box.

Function ProcessData() As Integer

Const conNoPreviousControl = 2483	' No previous control error.

On Error GoTo Process_Err

If Screen.PreviousControl.Name = "txtFinalEntry" Then

.	' Process Data Here.

.

.

ProcessData = True

Else

' Set Focus to txtFinalEntry and display message

Me!txtFinalEntry.Setfocus

MsgBox "Please enter a value here for further processing."

ProcessData = False

End If

Process_Bye:

Exit Function

Process_Err:

If Err = conNoPreviousControl Then

Me!txtFinalEntry.Setfocus

MsgBox "Please enter value to process"

ProcessData = False

End If

Resume Process_Bye

End Function


V1xNullBehavior Property (Microsoft Access)

You can use the V1xNullBehavior property to specify whether zero-length strings ("") used in code to fill Text or Memo fields are converted to Null.

Note   This property applies only to Microsoft Access version 1.x databases that have been converted to Microsoft Access version 2.0 databases and that contain such code. Microsoft Access automatically creates this property when it converts a version 1.x database to a version 2.0 database.

Setting

The V1xNullBehavior property uses the following settings.

Setting	Description

True (-1)	Zero-length strings are converted to Null.

False (0)	Zero-length strings aren't converted to Null.

You can set this property only using Visual Basic.

Note   If you change the setting for this property, you must close and then reopen the database for your change to take effect.

Remarks

For fastest performance, modify code that sets any Text or Memo fields to zero-length strings so the fields are set to Null, and remove the property from the Properties collection.


SelHeight, SelWidth Properties

You can use the SelHeight property to specify or determine the number of selected rows (records) in the current selection rectangle. You can use the SelWidth property to specify or determine the number of selected columns (fields) in the current selection rectangle. For example, if you have selected a group of rows and columns within Datasheet view of the Customers table, you can use the SelHeight and SelWidth properties to determine the number of rows and columns in the selection rectangle.

Setting

SelHeight [image] a Long Integer value between 0 and the number of selected rows in the selection rectangle.

SelWidth [image] a Long Integer value between 0 and the number of selected columns in the selection rectangle.

These properties are not available in Design view. These properties are only available in Visual Basic.

Remarks

If there is no selection, the value returned by these properties will be zero.

You can use these properties with the SelTop and SelLeft properties to specify or determine the actual position of the selection rectangle on the datasheet. If there is no selection, then these properties return the row number and column number of the cell with the focus.

The SelHeight and SelWidth properties contain the position of the lower-right corner of the selection rectangle. The SelTop and SelLeft property values determine the upper-left corner of the selection rectangle. If there is no selection, then the SelHeight and SelWidth properties are set to zero.


SelHeight, SelWidth, SelTop, and SelLeft Properties Example

The following example shows how to use the SelHeight, SelWidth, SelTop, and SelLeft properties to determine the position and size of a selection rectangle in datasheet view. The SetHeightWidth procedure assigns the height and width of the current selection rectangle to the variables lngHeight, lngWidth, lngTop, and lngLeft and displays those values in a message box.

Sub SetHeightWidth(frm As Form)

Dim lngNumRows As Long, lngNumColumns As Long

Dim lngTopRow As Long, lngLeftColumn As Long

Dim strMsg As String

If frm.CurrentView = 2 Then	' Form is in Datasheet view.

lngNumRows = frm.SelHeight	' Number of rows selected.

lngNumColumns = frm.SelWidth	' Number of columns selected.

lngTopRow = frm.SelTop	' Topmost row selected.

lngLeftColumn = frm.SelLeft	' Leftmost column selected.

strMsg = "Number of rows: " & lngNumRows & vbCrLf

strMsg = strMsg & "Number of columns: " & lngNumColumns & vbCrLf

strMsg = strMsg & "Top row: " & lngTopRow & vbCrLf

strMsg = strMsg & "Left column: " & lngLeftColumn

MsgBox strMsg

End If

End Sub


SelTop, SelLeft Properties

You can use the SelTop property to specify or determine which row (record) is topmost in the current selection rectangle. You can use the SelLeft property to specify or determine which column (field) is leftmost in the current selection rectangle. For example, if you have selected a group of rows and columns within Datasheet view of the Customer table, you can use the SelTop and SelLeft properties to determine the first row and first column selected in the selection rectangle.

Setting

SelTop [image] a Long Integer value between 0 and the number of the topmost row in the current selection rectangle.

SelLeft [image] a Long Integer value between 0 and the number of the leftmost column in the current selection rectangle.

These properties are not available in Design view. These properties are available only in Visual Basic.

Remarks

If there is no selection, the value returned by these properties is the row and column of the cell with the focus.

You can use these properties with the SelHeight and SelWidth properties to specify or determine the actual size of the selection rectangle. The SelTop and SelLeft properties determine the position of the upper-left corner of the selection rectangle. The SelHeight and SelWidth properties determine the lower-right corner of the selection rectangle.


CurrentRecord Property

Use the CurrentRecord property to identify the current record in the recordset being viewed on a form.

Setting

Microsoft Access sets this property to a Long Integer value that represents the current record number displayed on a form.

The CurrentRecord property is read-only in Form view and Datasheet view. It is not available in Design view. This property is available only in Visual Basic.

Remarks

The value specified by this property corresponds to the value shown in the record number box found in the lower-left corner of the form.


CurrentRecord Property Example

The following example shows how to use the CurrentRecord property to determine the record number of the current record being displayed. The general-purpose CurrentFormRecord procedure assigns the value of the current record to the variable recordnum.

Sub CurrentFormRecord(frm As Form)

Dim recordnum As Long

recordnum = frm.CurrentRecord

End Sub


InsideHeight, InsideWidth Properties

You can use the InsideHeight and InsideWidth properties to determine the height and width (in twips) of the window containing a form.

Setting

InsideHeight [image] an Integer value expressed in twips that represents the height of a form window.

InsideWidth [image] an Integer value expressed in twips that represents the width of a form window.

The InsideHeight and InsideWidth properties are available only in Visual Basic and can be set at any time.

Remarks

If you want to determine the interior dimensions of the form itself, use the Height and Width properties. The interior of a form is the region inside the form, excluding the scroll bars and the record selectors.

You can also use the WindowHeight and WindowWidth properties to determine the height and width of the window containing a form.


InsideHeight, InsideWidth Properties Example

The following example shows how to use the InsideHeight and InsideWidth properties to compare the inside height and width of a form with the height and width of the form's window. If the window's dimensions do not equal the size of the form, then the window is resized to match the form's height and width.

Sub ResetWindowSize(frm As Form)

Dim intWindowHeight As Integer

Dim intWindowWidth As Integer

Dim intTotalFormHeight As Integer

Dim intTotalFormWidth As Integer

Dim intHeightHeader As Integer

Dim intHeightDetail As Integer

Dim intHeightFooter As Integer

' Determine form's height.

intHeightHeader = frm.Section(1).Height

intHeightDetail = frm.Section(0).Height

intHeightFooter = frm.Section(2).Height

intTotalFormHeight = intHeightHeader _

+ intHeightDetail + intHeightFooter

' Determine form's width.

intTotalFormWidth = frm.Width

' Determine window's height and width.

intWindowHeight = frm.InsideHeight

intWindowWidth = frm.InsideWidth

If intWindowWidth <> intTotalFormWidth Then

intWindowWidth = intTotalFormWidth

End If

If intWindowHeight <> intTotalFormHeight Then

intWindowHeight = intTotalFormHeight

End If

End Sub


NewRecord Property

You can use the NewRecord property to determine whether the current record is a new record.

Setting

The NewRecord property has the following settings.

Setting	Description
True (-1)	The current record is new.
False (0)	The current record is not new.
The NewRecord property is read-only in Form view and Datasheet view. It is not available in Design view. This property is available only in macros, or Visual Basic.

Remarks

When a user has moved to a new record, the NewRecord property setting will be True whether the user has started to edit the record or not.


NewRecord Property Example

The following example shows how to use the NewRecord property to determine if the current record is a new record. The NewRecordMark procedure sets the current record to the variable newrec. If the record is new, a string is assigned to the string variable newmsg.

Sub NewRecordMark(frm As Form)

Dim newrec As Integer

Dim newmsg As String

newrec = frm.NewRecord

If newrec = True Then

newmsg = "new record"

End If

End Sub


StartupForm Property

You can use the StartupForm property to specify the name of the form that opens when your database first opens. For example, you can use this property to display a specified form that contains a menu of all available forms, queries, and reports within a Microsoft Access application when the database opens.

Setting

The StartupForm property is a string expression that is the name of a form in the current database.

You can set this property by using a macro or Visual Basic. You can also set this property using the Display Form option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

The StartupForm property is preferred over the OpenForm action in the AutoExec macro. Because Microsoft Access runs the AutoExec macro after it parses the startup properties, your application should not use an OpenForm action in its AutoExec macro if the StartupForm property is set.

If this property is blank, the Microsoft Access default database setting is used (the Database Window opens).

This property's setting does not take effect until the next time the application database opens.


Startup Properties Example

This example shows procedure named SetStartupProperties that passes the name of the property to be set, its datatype, and its desired setting. The general purpose procedure ChangeProperty attempts to set the startup property and, if the property is not found, uses the CreateProperty method to append it to the Database properties collection. This is necessary because these properties do not appear in the properties collection until they have been set or changed at least once.

Sub SetStartupProperties()

ChangeProperty "StartupForm", dbText, "Customers"

ChangeProperty "StartupShowDBWindow", dbBoolean, False

ChangeProperty "StartupShowStatusBar", dbBoolean, False

ChangeProperty "AllowBuiltinToolbars", dbBoolean, False

ChangeProperty "AllowFullMenus", dbBoolean, True

ChangeProperty "AllowBreakIntoCode", dbBoolean, False

ChangeProperty "AllowSpecialKeys", dbBoolean, True

ChangeProperty "AllowBypassKey", dbBoolean, True

End Sub

Function ChangeProperty(strPropName As String, varPropType As Variant, varPropValue As Variant) As Integer

Dim dbs As Database, prp As Property

Const conPropNotFoundError = 3270

Set dbs = CurrentDb

On Error GoTo Change_Err

dbs.Properties(strPropName) = varPropValue

ChangeProperty = True

Change_Bye:

Exit Function

Change_Err:

If Err = conPropNotFoundError Then  'prop not found

Set prp = dbs.CreateProperty(strPropName, _

varPropType, varPropValue)

dbs.Properties.Append prp

Resume Next

Else

'unkown error

ChangeProperty = False

Resume Change_Bye

End If

End Function


StartupMenuBar Property

You can use the StartupMenuBar property to specify the menu bar macro that creates the global menu bar for your application. For example, you can use the StartupMenuBar property to display a custom menu bar that does not contain the Security menu. This prevents a user from accessing any of the Security menu commands from the menu bar.

Setting

The StartupMenuBar property is a string expression that is the name of a menu bar macro in the current database.

You can set this property by using a macro or Visual Basic. You can also set this property using the Menu Bar option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

If you are setting the StartupMenuBar property, you should not use a SetValue action in the AutoExec macro to set the MenuBar property for the Application object. Since Microsoft Access runs the AutoExec macro after it parses the startup properties, the global menu bar set in the AutoExec macro would replace the menu set by the StartupMenuBar property.

You can also create custom menu bars using the MenuBar property for forms and reports. These custom menu bars are displayed when a specific form or report opens and replace the global menu bar in those cases.

If the StartupMenuBar property is blank, Microsoft Access displays the built-in menu bar. If this property is not blank (default) then the setting of the AllowFullMenus property has no effect.

This property's setting does not take effect until the next time the application database opens.

Setting this property has the same effect as setting the MenuBar property of Application object (except the MenuBar property setting takes effect immediately).


StartupShortcutMenuBar Property

You can use the StartupShortcutMenuBar property to specify the shortcut menu bar macro that is the global menu for your application.

Setting

The StartupShortcutMenuBar property is a string expression that is the name of a menu bar macro that displays a custom shortcut menu bar.

You can set this property by using a macro or Visual Basic code. You can also set this property using the Shortcut option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

If you are setting the StartupShortcutMenuBar property, you should not use a SetValue action in the AutoExec macro to set the ShortcutMenuBar property for the Application object. Since Microsoft Access runs the AutoExec macro after it parses the startup properties, the global shortcut menu set in the AutoExec macro would replace the shortcut menu set in the StartupShortcutMenuBar property.

You can also create custom shortcut menu bars using the ShortcutMenubar property for forms, reports, and controls. These custom shortcut menu bars are displayed when you use the right mouse button to click in a specific form, report, or control.

If this property is blank, Microsoft Access displays the built-in shortcut menu bar.

This property's setting does not take effect until the next time the application database opens.

Setting this property has the same effect as setting the ShortcutMenuBar property of Application object (except the ShortcutMenuBar property setting takes effect immediately).


StartupShowDBWindow Property

You can use the StartupShowDBWindow property to specify whether or not the Database window is displayed when your application database opens. For example, you can open a main form when your application database opens and hide the Database window.

Setting

The StartupShowDBWindow property has the following settings.

Setting	Description
True (-1)	Display the Database window at startup.
False (0)	Don't display the Database window at startup.
You can set this property by using a macro or Visual Basic. You can also set this property using the Display Database Window option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

You can set the StartupShowDBWindow property to False to hide the Database window so the user cannot see the tables, queries, macros, and modules within your database.

This property's setting does not take effect until the next time the database opens.


StartupShowStatusBar Property

You can use the StartupShowStatusBar property to specify whether or not the status bar should appear when the application database opens. For example, you can use the StartupShowStatusBar property to prevent display of the status bar if you do not want to display any status messages in your application.

Setting

The StartupShowStatusBar property has the following settings.

Setting	Description
True (-1)	Display the status bar at startup.
False (0)	Don't display the status bar at startup.
You can set this property by using a macro or Visual Basic. You can also set this property using the Display Status Bar option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

This property's setting does not take effect until the next time the application database opens.


AllowBuiltInToolbars Property

You can use the AllowBuiltInToolbars property to specify whether or not the user can display Microsoft Access built-in toolbars. For example, you can use the AllowBuiltInToolbars property to prevent a user from seeing a Microsoft Access built-in toolbar within a database application.

Setting

The AllowBuiltInToolbars property has the following settings.

Setting	Description
True (-1)	Allow built-in toolbars to be displayed.
False (0)	Don't allow built-in toolbars to be displayed.
You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Default Toolbars option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

If the AllowBuiltInToolbars property is set to False, clicking Toolbars on the View menu will not display any built-in toolbars.

The user can modify built-in toolbars only when the AllowToolbarChanges property is set to True and the AllowBuiltInToolbars property is set to True.

This property setting has no effect on the ShowToolbar action. If the AllowBuiltInToolbars property is set to False, no toolbar is displayed.

This property's setting does not take effect until the next time the application database opens.


AllowFullMenus Property

You can use the AllowFullMenus property to specify whether or not full Microsoft Access built-in menus will be available when the application database opens. For example, you can use the AllowFullMenus property to disable menu items that give users the ability to modify table, form, query, or report structures.

Setting

The AllowFullMenus property uses the following settings.

Setting	Description
True (-1)	Display the full built-in menus at startup.
False (0)	Don't display full built-in menus at startup.
You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Full Menus option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

This property's setting does not take effect until the next time the database opens.


AllowToolbarChanges Property

You can use the AllowToolbarChanges property to specify whether or not your database allows users to customize toolbars. For example, you can use the AllowToolbarChanges property to prevent users from deleting a toolbar button or an entire toolbar from your application.

Setting

The AllowToolbarChanges property uses the following settings.

Setting	Description
True (-1)	Allow changes to toolbars.
False (0)	Don't allow changes to toolbars.
You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Toolbar Changes option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

Setting the AllowToolbarChanges property to False prevents users from modifying any toolbars. It disables the Toolbars command on the View menu, the right-click menu feature on toolbars, and all Close buttons on toolbars displayed in the Microsoft Access window.

The user can modify built-in toolbars only when the AllowToolbarChanges property is True and the AllowBuiltInToolbars is True.

This property's setting does not take effect until the next time the database opens.


AllowShortcutMenus Property

You can use the AllowShortcutMenus property to specify whether or not your application allows Microsoft Access to display shortcut menus. For example, you can use the AllowShortcutMenus property to prevent the user from using any shortcut menu within your application.

Setting

The AllowShortcutMenus property uses the following settings.

Setting	Description
True (-1)	Allow Microsoft Access shortcut menus to be displayed.
False (0)	Don't allow Microsoft Access shortcut menus to be displayed.
You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Default Shortcut Menus option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

This property's setting does not take effect until the next time the database opens.


AllowBreakIntoCode Property

You can use the AllowBreakIntoCode property to specify whether or not the user can view Visual Basic code after a run-time error occurs in a module.

Setting

The AllowBreakIntoCode property uses the following settings.

Setting	Description
True (-1)	Enable the Debug button on the dialog box that appears when a run-time error occurs.
False (0)	Disable the Debug button.
You can set this property by using a macro or Visual Basic. You can also set this property using the Allow Viewing Code After Error option in the Advanced section of the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

You should not disable the AllowBreakIntoCode property when debugging application or macros.

This property's setting does not take effect until the next time the application database opens.


AllowSpecialKeys Property

You can use the AllowSpecialKeys property to specify whether or not special key sequences (ALT+F1 (F11), CTRL+F11, CTRL+BREAK, and CTRL+G) are disabled or enabled. For example, you can use the AllowSpecialKeys property to prevent a user from displaying the Database window using F11, entering break mode within a Visual Basic module using CTRL+BREAK, or displaying the Debug window using CTRL+G.

Setting

The AllowSpecialKeys property uses the following settings.

Setting	Description
True (-1)	Enable the special key sequences.
False (0)	Disable the special key sequences.
You can set this property by using a macro or Visual Basic. You can also set this property by selecting Use Access Special Keys in the Advanced section of the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

Remarks

You should enable the AllowSpecialKeys property when debugging your database.

The AllowSpecialKeys property affects the following key sequences.

Key sequences	Effect
ALT+F1 (F11)	Bring the Database window to the front.
CTRL+G	Display the Debug window.
CTRL+F11	Toggle between the custom menu bar and the built-in menu bar.
CTRL+BREAK	Enter break mode.
This property's setting does not take effect until the next time the application database opens


AllowBypassKey Property

You can use the AllowBypassKey property to specify whether or not the SHIFT key is enabled for bypassing the startup properties or the AutoExec macro. For example, you can set the AllowBypassKey property to False to prevent a user from bypassing the startup properties and the AutoExec macro.

Setting

The AllowBypassKey property uses the following settings.

Setting	Description
True (-1)	Enable the SHIFT key to allow the user to bypass the startup properties or the AutoExec macro.
False (0)	Disable the SHIFT key to prevent the user from bypassing the startup properties or the AutoExec macro.
You can set this property by using a macro or Visual Basic.

Remarks

You should enable the AllowBypassKey property when debugging your database.

This property's setting does not take effect until the next time the application database opens.


AppIcon Property

You can use the AppIcon property to specify the name of the bitmap (.bmp) or icon (.ico) file that contains the application's icon. For example, you can use the AppIcon property to specify a .bmp file that contains an picture of an automobile to represent an automotive parts application.

Setting

The AppIcon property is a string expression that is a bitmap or icon filename.

You can set this property by using a macro or Visual Basic. You can also set this property using the Application Icon option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

To set the AppIcon property using Visual Basic you must first create the property using the CreateProperty method and append it to the Database properties collection.

Remarks

This property setting takes effect immediately after it is set in code or the Startup dialog box is closed.

If you are distributing your application, it is recommended that the .bmp or .ico file containing the icon reside in the same directory as your Microsoft Access application.

If the AppIcon property is not set or is invalid, the Microsoft Access icon is displayed.


AppIcon, AppTitle Properties Example

The following example shows how to change the AppIcon and AppTitle properties. If the properties have not already been set or created, you must create them and append them to the Database object using the CreateProperty method.

Sub cmdAddProp_Click()

Dim x As Integer

x = AddAppProperty("AppTitle", dbText, "My Custom Application")

x = AddAppProperty("AppIcon", dbText, "C:\Windows\Cars.bmp")

End Sub

Function AddAppProperty(prpName As String, prpType As Variant, prpValue As Variant) As Integer

Dim dbs As Database, prp As Property

Const conPropNotFoundError = 3270

Set dbs = CurrentDb

On Error GoTo AddProp_Err

dbs.Properties(prpName) = prpValue

AddAppProperty = True

AddProp_Bye:

Exit Function

AddProp_Err:

If Err = conPropNotFoundError Then

Set prp = dbs.CreateProperty(prpName, prpType, prpValue)

dbs.Properties.Append prp

Resume

Else

AddAppProperty = False

Resume AddProp_Bye

End If

End Function


AppTitle Property

You can use the AppTitle property to specify the text that appears in the application database's title bar. For example, you can use the AppTitle property to specify that the string "Inventory Control" appear in the title bar of your Inventory Control database application.

Setting

The AppTitle property is a string expression containing the text to appear in the title bar.

You can set this property by using a macro or Visual Basic. You can also set this property using the Application Title option in the Startup dialog box, available by clicking Startup on the Tools menu. This is the easiest way to set this property.

To set the AppTitle property using Visual Basic you must first create the property using the CreateProperty method and append it to the Database properties collection. You must also use the RefreshTitleBar method to make any changes visible.

Remarks

If this property is not set, the string "Microsoft Access" appears in the title bar.

This property's setting takes effect immediately after setting the property in code or closing the Startup dialog box.


DisplayType Property

You can use the DisplayType property to specify whether Microsoft Access displays an OLE object's content or an icon. For example, if the OLE object is a Microsoft Word document and you set this property to Content, the control displays the Word document; if you set this property to Icon, the control displays the Word icon.

Setting

The DisplayType property uses the following settings.

Setting	Description	Visual Basic
Content	(Default) When the control contains an OLE object, the control displays the object's data, such as a document or spreadsheet.	acOLEDisplayContent (0)
Icon	When the control contains an OLE object, the control displays the object's icon.	acOLEDisplayIcon (1)
You can set the DisplayType property using the property sheet, a macro, or Visual Basic. You can also set this property in a control's default control style.

For a bound object frame, the DisplayType property can be set only in Design view but can be read in all views. For an unbound object frame or chart, the property can be set in the Insert Object dialog box when the object is created.

Remarks

The DisplayType property determines the default setting of the Display As Icon check box in the Paste Special and Object dialog boxes. When you display these dialog boxes in Form view, Datasheet view, or Design view, the Display As Icon check box is automatically selected if the DisplayType property is set to Icon. For example, you will see these boxes selected when using Visual Basic to set the control's Action property to acOLEInsertObjDlg or acOLEPasteSpecialDlg.

The DisplayType property setting has no effect on the state of the Display As Icon check box in the Object dialog box when you insert an object into an unbound object frame. When you paste an object from the Clipboard, the Display As Icon check box reflects the state of the object on the Clipboard.

Changing the DisplayType property of a bound object frame doesn't affect the display of existing objects in the control; however, it will affect new objects that you add to the control using the Object command on the Insert menu.


SizeMode Property

You can use the SizeMode property to specify how to size a picture or other object in a bound object frame, an unbound object frame, or an image control.

Setting

The SizeMode property uses the following settings.

Setting	Description	Visual Basic
Clip	(Default) Displays the object at actual size. If the object is larger than the control, its image is clipped on the right and bottom by the control's borders.	0
Stretch	Sizes the object to fill the control. This setting may distort the proportions of the object.	1
Zoom	Displays the entire object, resizing it as necessary without distorting the proportions of the object. This setting may leave extra space in the control if the control is resized.	3
You can set the SizeMode property using the property sheet, a macro, or Visual Basic. You can also set this property in a control's default control style.

Tip   Use the Clip setting for the fastest display. You can use the Stretch setting for bar graphs and line graphs without concern for size adjustments. The Stretch setting can distort circles and photos.


SourceDoc Property

You can use the SourceDoc property to specify the file to be linked or embedded when you create a linked object or embedded object using the Action property in Visual Basic.

Setting

For an embedded object, enter the filename for the file you want to use as a template and set the Action property to acOLECreateEmbed.

For a linked object, enter the full path and filename for the file to be linked and set the Action property to acOLECreateLink.

You can set this property using the property sheet, a macro, or Visual Basic.

Note   While this property appears in the property sheet, it takes effect only when used with the Action property in Visual Basic.

Remarks

You can use the SourceDoc property to specify the file to be linked and the control's SourceItem property to specify the data within that file. If you want to link the entire object, leave the SourceItem property blank.

When a linked unbound object is created, the control's SourceItem property setting is concatenated with its SourceDoc property setting. In Form view, Datasheet view, and Print Preview, the control's SourceItem property setting is a zero-length string (" "), and its SourceDoc property setting is the full path to the linked file, followed by an exclamation point (!) or a backslash (\) and the SourceItem property setting as in the following example.

"C:\Work\Qtr1\Revenue.xls!R1C1:R30C15"


SourceDoc, SourceItem, Action, Class, OLETypeAllowed, SizeMode Properties Example

The following example creates a linked OLE object and sizes the control to display the object's entire contents when the user clicks a command button.

Sub Command1_Click

OLE1.Class = "Excel.Sheet"	' Set class name.

OLE1.OLETypeAllowed = acOLELinked	' Specify type of object.

OLE1.SourceDoc = "C:\Excel\Oletext.xls"	' Specify source file.

OLE1.SourceItem = "R1C1:R5C5"	' Specify data to link.

OLE1.Action = acOLECreateLink	' Create linked object.

OLE1.SizeMode = acOLESizeZoom	' Adjust control size.

End Sub


UpdateOptions Property

You can use the UpdateOptions property to specify how a linked OLE object is updated.

Setting

The UpdateOptions property uses the following settings.

Setting	Description	Visual Basic
Automatic	(Default) Updates the object each time the linked data changes.	0
Manual	Updates the object only when the control's Action property is set to acOLEUpdate or the link is updated with the OLE/DDE Links command on the Edit menu.	2
You can set the UpdateOptions property using the property sheet, a macro, or Visual Basic. You can also set this property in a control's default control style.

The UpdateOptions property setting is also available through the OLE/DDE Links command on the Edit menu.

Remarks

Normally, the object is updated automatically whenever the linked data changes, but you can tell Microsoft Access to update the data only when it receives a specific instruction to do so. For example, if other users or applications can access or change linked spreadsheet data on a form, you can use this property to specify that the linked data only be updated when the database is opened in single-user mode.

When the UpdateOptions property is set to Manual, updates do not occur based on the Refresh Interval setting specified in the Advanced tab of the Options dialog box, available by clicking Options on the Tools menu.

Note   When an object's data is changed, the Updated event occurs.


UpdateOptions Property Example

The following example sets the UpdateOptions property for an unbound object frame named OLE1 to update manually, and then uses the Action property to force an update of the OLE object in the control.

OLE1.UpdateOptions = 2

OLE1.Action = acOLEUpdate


ForceNewPage Property

You can use the ForceNewPage property to specify whether form (header, detail, footer) or report (header, detail, footer) sections print on a separate page, rather than on the current page. For example, you may have designed the last page of a report as an order form. If the report footer's ForceNewPage property is set to Before Section, the order form is always printed on a new page.

Note   The ForceNewPage property does not apply to page headers or page footers.

Setting

The ForceNewPage property uses the following settings.

Setting	Description	Visual Basic
None	(Default) The current section (the section for which you're setting the property) is printed on the current page.	0
Before Section	The current section is printed at the top of a new page.	1
After Section	The section immediately following the current section is printed at the top of a new page.	2
Before & After	The current section is printed at the top of a new page, and the next section is printed at the top of a new page.	3
You can set this property using the section's property sheet, a macro, or Visual Basic.

Remarks

Here are some examples of the ForceNewPage property setting.

Section	Sample setting	Description
A group header displaying the year	Before Section	The group header is printed at the top of the page, followed by the detail section, group footer, and page footer.
A report detail section	After Section	The group footer is printed at the top of a new page.
A report header containing the report title and company logo.	After Section	The report title and logo are printed on a separate page at the beginning of the report.


ForceNewPage Property Example

The following example returns the ForceNewPage property setting for the detail section of the Sales By Date report and assigns it to the intGetVal variable.

Dim intGetVal As Integer

intGetVal = Reports![Sales by Date].Section(0).ForceNewPage


HideDuplicates Property

You can use the HideDuplicates property to hide a control on a report when its value is the same as in the preceding record. For example, on a report listing suppliers and their products, each supplier's name can appear once for each group of products, rather than once for each product.

Note   The HideDuplicates property applies only to controls (check box, combo box, list box, option button, option group, text box, toggle button) on a report.

The property doesn't apply to check boxes, option buttons, or toggle buttons when they appear in an option group. It does apply to the option group itself.

Setting

The HideDuplicates property uses the following settings.

Setting	Description	Visual Basic
Yes	If the value of a control or the data it contains is the same as in the preceding record, the control is hidden. (To determine the control's value, see the Remarks section.)	True (-1)
No	(Default) The control is visible regardless of the value in the preceding record.	False (0)
You can set this property using the control's property sheet, a macro, or Visual Basic.

You can set the HideDuplicates property only in report Design view.

Remarks

You can use the HideDuplicates property to create a grouped report using only the detail section rather than a group header and the detail section.


HideDuplicates Property Example

The following example returns the HideDuplicates property setting for the CategoryName text box and assigns the value to the intCurVal variable.

Dim intCurVal As Integer
intCurVal = Me![CategoryName].HideDuplicates


KeepTogether Property - Sections
KeepTogether Property — Sections

You can use the KeepTogether property to print a report section all on one page. For example, you might have a group of related information that you don't want printed across two pages.

Note   The KeepTogether property applies only to forms and reports sections (except page headers and page footers).

Setting

The KeepTogether property uses the following settings.

Setting	Description	Visual Basic
Yes	Microsoft Access starts printing the section at the top of the next page if it can't print the entire section on the current page.	True (-1)
No	(Default) Microsoft Access prints as much of the section as possible on the current page and prints the rest on the next page.	False (0)
You can set this property using the section's property sheet, a macro, or Visual Basic.

You can set the KeepTogether property only in report Design view.

Remarks

Usually, when a page break occurs while a section is being printed, Microsoft Access continues printing the section on the next page. Using the section's KeepTogether property, you can print the section all on one page. If a section is longer than one page, Microsoft Access starts printing it on the next page and continues on the following page.


KeepTogether Property - Sections Example
KeepTogether Property — Sections Example

This example returns the KeepTogether property setting for the report's detail section and assigns the value to the intGetVal variable.

Dim intGetVal As Integer

intGetVal = Me.Section(0).KeepTogether


NewRowOrCol Property

You can use the NewRowOrCol property to specify whether a section and its associated data is printed in a new row or column within a multiple-column report. For example, you can use this property to print each group header at the top of a new column in a multiple-column report.

Note   The NewRowOrCol property does not apply to page headers or page footers.

Setting

The NewRowOrCol property uses the following settings.

Setting	Description	Visual Basic
None	(Default) The row or column breaks are determined by the settings in the Print Setup dialog box and the available space on the page.	0
Before Section	Microsoft Access starts printing the current section (the section for which you're setting the property, such as a group header section) in a new row or column. It then prints the next section, such as a detail section, in that same row or column.	1
After Section	Microsoft Access starts printing the current section, such as a group header section, in the current row or column. It starts printing the next section, such as a detail section, in the next row or column.	2
Before & After	Microsoft Access starts printing the current section in a new row or column. It starts printing the following section in the next row or column.	3
You can set this property using the section's property sheet, a macro, or Visual Basic.

You can set the NewRowOrCol property only in report Design view.

Remarks

The following items are some sample settings for a group header section in a multiple-column report. The Layout Items option in the Layout tab of the Page Setup dialog box (available by clicking Page Setup on the File menu) should be set to Down, Then Across.

Sample setting	Result

Before Section	The group header is printed at the top of a new column.

After Section	The detail section is printed at the top of a new column.

Before & After	The group header is printed in a column by itself, and the detail section is printed at the top of a new column.

Report sections in a form or report are normally printed vertically down a page. The default Layout Items option is Across, Then Down. You can print the sections in multiple columns across a page by setting the Layout Items option in the Layout tab of the Page Setup dialog box to Down, Then Across.

When you set the NewRowOrCol property to Before Section, the vertical or horizontal orientation of the page affects how the section is printed. If you select Across, Then Down in the Layout Items option in the Layout tab of the Page Setup dialog box, Microsoft Access starts printing the section at the beginning of a new row; if you select Down, Then Across, Microsoft Access starts printing the section at the beginning of a new column.


NewRowOrCol Property Example

The following example returns the NewRowOrCol property setting and assigns it to the intGetVal variable.

Dim intGetVal As Integer

intGetVal = Reports!MyReport.Section(1).NewRowOrCol

The next example presents two layouts for a report that divides data into four groups (Head1 to Head4). Each group includes three to six records, and each record has field a and field b. The layouts differ only in their Layout Items option in the Layout tab of the Page Setup dialog box and the values of their NewRowOrCol properties.

Layout Items [image] Across, Then Down Grid Settings [image] Items Across set to 4 NewRowOrCol property setting for group header section [image] Before & After Head1 1a 1b 2a 2b 3a 3b 4a 4b 5a 5b Head2 1a 1b 2a 2b 3a 3b 4a 4b Head3 1a 1b 2a 2b 3a 3b Head4 1a 1b 2a 2b 3a 3b 4a 4b 5a 5b 6a 6b	Layout Items [image] Down, Then Across Grid Settings [image] Items Across set to 4 NewRowOrCol property setting for group header section [image] Before Section Head1 Head2 Head3 Head4 1a 1b 1a 1b 1a 1b 1a 1b 2a 2b 2a 2b 2a 2b 2a 2b 3a 3b 3a 3b 3a 3b 3a 3b 4a 4b 4a 4b 4a 4b 5a 5b 5a 5b 6a 6b


Page, Pages Properties

You can use the Page and Pages properties to return information needed to print page numbers in a form or report. For example, you could use these properties to print "Page n of nn" in the page footer of a report.

Page [image] This property specifies the current page number when a form or report is being printed.

Pages [image] This property specifies the total number of pages in a form or report.

Setting

Although you can set the Page property to an Integer value, you most often use these properties to return information about page numbers. Both properties return an Integer value when used in an expression.

You can use the Page and Pages properties in an expression, a macro, or an event procedure.

These properties are only available in Print Preview or when printing.

The Pages property is read-only at all times.

Remarks

To refer to the Pages property in a macro or Visual Basic, the form or report must include a text box whose ControlSource property is set to an expression that uses Pages. For example, you can use the following expressions as the ControlSource property setting for a text box in a page footer.

This expression	Prints

=Page	A page number (for example, 1, 2, 3) in the page footer.

="Page " & Page & " of " & Pages	"Page n of nn" (for example, Page 1 of 5, Page 2 of 5) in the page footer.

=Pages	The total number pages in the form or report (for example, 5).


Page, Pages Properties Example

The following example displays a message that tells how many pages the report contains. For this example to work, the report must include a text box for which the ControlSource property is set to the expression =Pages.

Dim intTotalPages As Integer, strMsg As String

intTotalPages = Reports![Report1].Pages

strMsg = "This report contains " & intTotalPages & " pages."

MsgBox strMsg


PageHeader, PageFooter Properties

You can use the PageHeader and PageFooter properties to specify whether a report's page header or page footer are printed on the same page as a report header or report footer. For example, you might not want to print a page header containing the page number on the first page of a report if the report header is a cover sheet.

Setting

The PageHeader and PageFooter properties use the following settings.

Setting	Description	Visual Basic
All Pages	(Default) The page header or footer is printed on all pages of a report.	0
Not With Rpt Hdr	The page header or footer isn't printed on the same page as the report header. Microsoft Access prints the report header on a new page.	1
Not With Rpt Ftr	The page header or footer isn't printed on the same page as the report footer. Microsoft Access prints the report footer on a new page.	2
Not With Rpt Hdr/Ftr	The page header or footer isn't printed on a page that has either a report header or a report footer. Microsoft Access prints the report header or footer on a new page.	3
You can set these properties using the report's property sheet, a macro, or Visual Basic.

You can set the PageHeader and PageFooter properties only in report Design view.

Remarks

Microsoft Access normally prints report page headers or page footers on every page in a report, including the first and last.

In report Design view, click Page Header/Footer on the View menu to display the page header and page footer sections.

Note   When forms are printed, page headers and page footers are always printed on all pages.


PageHeader, PageFooter Properties Example

The following example sets the PageHeader property for a report to Not With Rpt Hdr. To run this example, type the following line in the Debug window for a report named Report1.

Reports![Report1].PageHeader = 1


Alias Property

You can use the Alias property to specify a custom name for an input table or query when you use the same table or query more than once in the same query.

Note   The Alias property applies only to tables or queries when used as the source of data in a query.

Setting

You can set the Alias property using a string expression to any name not currently being used in the database. You set this property in query design view by right clicking on the field list in the query design grid and choosing Properties.

You can set the Alias property in SQL view of the Query window by using an AS clause in the SQL statement.

Remarks

You must use an alias when creating self-join in an SQL statement.

When you add a table or query to a query, Microsoft Access automatically sets the Alias property to the name of the table or query. If a second instance of the same table or query is added, Microsoft Access sets the Alias as the object name plus an underscore and a one ("_1").

Creating an alias doesn't change the name of the table or query [image] it only specifies another name that can also be used to refer to the table or query. For example, in a query containing a self-join that shows employees and their managers, you would use two copies of the Employees table. Microsoft Access automatically calls the duplicate table Employees_1. To give this table a more meaningful name, you could set its Alias property to Managers.


Alias Property Example

The following example sets the RecordSource property for a form to an SQL statement that uses the AS clause to specify Managers as the alias for the Employees table.

Dim strGetSQL AS String

strGetSQL = "SELECT DISTINCTROW Employees.[FirstName], Employees.[LastName], _

Employees.Title, Managers.[FirstName], Managers.[LastName] FROM Employees _

INNER JOIN Employees AS Managers ON Employees.[ReportsTo] = Managers.[EmployeeID]; "

Forms!Form1.RecordSource = strGetSQL

This example uses a self-join to show employees and their managers. It uses the AS clause to set the Alias property of the duplicate Employees table to Managers. You can enter this SQL statement in SQL view of the Query window.

SELECT DISTINCTROW Employees.[FirstName], Employees.[LastName],
Employees.Title, Managers.[FirstName], Managers.[LastName]
FROM Employees INNER JOIN Employees AS Managers ON Employees.[ReportsTo] = Managers.[EmployeeID];


ColumnHeadings Property

You can use the ColumnHeadings property to specify the order or limit the number of columns displayed in a crosstab query. For example, in a query that displays the names of countries, you may want to show them in a specific order, such as United States first, Canada second, and the United Kingdom third.

Note   The ColumnHeadings property applies only to crosstab queries.

Setting

Enter the data values from the column headings field as a string expression in the order you want them displayed in the datasheet for the crosstab query, separated by a comma (or the list separator set in the Regional Settings section of the Windows Control Panel). The following table shows sample ColumnHeadings settings and the result in the crosstab query's datasheet.

Sample setting	Result

"Qtr 1", "Qtr 2", "Qtr 3", "Qtr 4"	Displays column headings for each quarter

"Mexico", "Canada", "USA"	Displays column headings for each country

You can set this property using the query property sheet or Visual Basic. You can also set it in SQL view of the Query window by using a PIVOT clause in the SQL statement.

Note   The column headings you specify for the ColumnHeadings property must exactly match the data values in the column headings field in the query design grid.

Remarks

You use the ColumnHeadings property to obtain more control over the appearance of column headings in a crosstab query. By default, Microsoft Access displays all data values as column headings in ascending order. For example, if your column heading field name is Month, the default column headings displayed will be April, August, December, February, and so on. You can use the ColumnHeadings property to display the data in the correct order with the appropriate setting: "January", "February", "March", and so on.

If you include a column heading in the ColumnHeadings property setting, the column is always displayed in query Datasheet view, even if the column contains no data. This is useful for a report based on a crosstab query, for example, when you always want to display the same column headings in the report.

Tip   You can use the ColumnHeadings property to improve the speed of some crosstab queries by limiting the number of columns displayed.


ColumnHeadings Property Example

This example creates four column headings (Qtr 1, Qtr 2, Qtr 3, Qtr 4) in Datasheet view of the crosstab query listing the quarterly orders by product. You can enter this statement in SQL view of the Query window.

TRANSFORM Sum(CCur([Order Details].[UnitPrice]*[Order Details].[Quantity]*(1-[Discount])/100)*100)
AS [Product Amount]
SELECT Products.ProductName FROM Products
INNER JOIN (Orders INNER JOIN [Order Details]
ON Orders.OrderID = [Order Details].OrderID) ON Products.ProductID = [Order Details].ProductID
WHERE (((Orders.ShippedDate) Between #1/1/94# And #12/31/94#))
GROUP BY Products.ProductName
PIVOT "Qtr " & DatePart("q",[ShippedDate],1,0);


OutputAllFields Property

You can use the OutputAllFields property to show all fields in the query's underlying data source and in the field list of a form or report. Setting this property is an easy way to show all fields without having to check the Show box in the query design grid for each field in the query.

Note   The OutputAllFields property applies only to append, make-table, and select queries.

Setting

The OutputAllFields property uses the following settings.

Setting	Description

Yes	Displays all the fields in the underlying tables and in the field list of a form or report.

No	(Default) Displays only fields having the Show box selected in the query design grid.

You can set this property in the query property sheet or in SQL view of the Query window.

Note   An asterisk (*) in the SQL statement in place of a field name is the equivalent of setting the OutputAllFields property to Yes.

Remarks

When OutputAllFields is set to Yes, the only fields you need to include in the query design grid are those that you want to sort on or specify criteria for.

When you save a filter as a query, Microsoft Access sets OutputAllFields to Yes.


OutputAllFields Property Example

The following example uses an asterisk in an SQL statement to select all the fields in the Shippers table. It then displays the fields in text boxes on a form by setting the ControlSource property for the text boxes to the names of the individual fields in the query.

Dim strGetSQL AS String
strGetSQL = "SELECT * FROM Shippers"
Forms!Form1.RecordSource = strGetSQL
Text1.ControlSource = "ShipperID"
Text2.ControlSource = "CompanyName"

In the output for the next SQL statement, the values in the CompanyName and ProductName fields are sorted in ascending order, and all the fields in the Suppliers and Products tables are displayed in the field lists and in Datasheet view. You can enter this SQL statement in SQL view of the Query window.

SELECT DISTINCTROW *
FROM Suppliers
INNER JOIN Products ON Suppliers.[SupplierID] = Products.[SupplierID]
ORDER BY Suppliers.[CompanyName], Products.[ProductName];


ReturnsRecords Property (Microsoft Access)

You can use the ReturnsRecords property in an SQL pass-through query to specify whether the query returns records. For example, if your pass-through query is SELECT * FROM EMPLOYEES, you can set the ReturnRecords property to Yes to display all employee records in the query's datasheet.

Note   The ReturnsRecords property applies only to pass-through queries.

Setting

The ReturnsRecords property uses the following settings.

Setting	Description	Visual Basic
Yes	(Default) The query returns records (like a select query).	True (-1)
No	The query doesn't return records (like an action query).	False (0)
You can set this property in the query property sheet or in Visual Basic.

Tip   You can access a pass-through query's ReturnsRecords property in Visual Basic, but the preferred method is to use the data access ReturnsRecords property.

Remarks

A pass-through query can return records, or it can be used to change data, create a database object, or perform an action like an action query.

When you set the ReturnsRecords property to Yes, you can use the pass-through query in another query or as the basis for a combo box, list box, form, or report. If you set the ReturnsRecords property to No, you can't use the query as the basis for an object or control because no records are returned.


RunPermissions Property

You can use the RunPermissions property in a multiuser environment with a secure workgroup to override the existing user permissions. This allows you to view a query or run an append, delete, make-table, or update query that you otherwise would not have permission to run. For example, as a user, you may have read-only permission for queries, while the owner of the queries has read/write permission. If the owner set the RunPermissions property to specify the owner's permissions, you can run an append query to add records to a table.

Note   The RunPermissions property applies only to append, crosstab, delete, make-table, select, and update queries.

Setting

The RunPermissions property uses the following settings.

Setting	Description

Owner's	All users are allowed the owner's permissions to view or run the query.

User's	(Default) Users have only their own permissions to view or run the query.

You can set this property using the query property sheet.

You can also set the RunPermissions property in SQL view of the Query window by using the WITH OWNERACCESS OPTION declaration in the SQL statement.


RunPermissions Property Example

The following example is a select query based on the Categories table that enables all users to have the owner's permissions for the query.

SELECT DISTINCTROW Categories.[CategoryID], _

Categories.[CategoryName], Categories.Description
FROM Categories
WITH OWNERACCESS OPTION;


Source Property (Microsoft Access)

You can use the Source property to specify the source connection string and source database for a query's input table or query. This is necessary if you are accessing data in an external table without linking the table.

Note   Using the Source property and the SourceConnectStr property to access ODBC tables is much slower than using linked tables.

Setting

You set the Source property using a string expression. The following examples show how you can use the Source property to connect to several different types of external databases.

Type of database	Specify this	Sample setting
Microsoft Access	The path and database name. Microsoft Access adds the filename extension automatically.	C:\Accts\Customers
dBASE	The database type and path. For a list of specifiers, see the Connect property.	dBASE IV;DatabaseTable=C:\DBDATA
SQL Server (ODBC)	The name of the source database and any additional information required by the product, such as a logon identification (ID) and password. You can also use the ODBC Connection String Builder to create the connection string.	ODBC;DSN=salessrv;UID=jace; PWD=password;DATABASE=sales;
You can set this property in a query's field list property sheet.

You can also set it in SQL view of the Query window by using the FROM and IN clauses in the SQL statement.

Remarks

When all the input tables in a query come from the same external database, use the query's SourceConnectStr and SourceDatabase properties instead of setting the Source property for each input table or query.


Source Property Example

You can't set this property in code directly. It's set when you create a new query using an SQL statement. The FROM clause in the SQL statement corresponds to the Source property setting.

The following example sets the ControlSource property for a text box to a field in a dBASE IV table.

Dim strGetSQL AS String
strGetSQL = "SELECT DISTINCTROW Customers.[Company Name], _

FROM [dBASE IV; DATABASE = c:\dbdata].Customers;"
Forms!Customers.txtCompanyName.ControlSource = strGetSQL

In the next example, the source of data for the query is a dBASE IV table named Customers in the C:\Dbdata directory. You can enter this SQL statement in SQL view of a Query window.

SELECT DISTINCTROW Customers.[Company Name], Customers.Phone
FROM [dBASE IV; DATABASE = c:\dbdata].Customers;


TopValues Property

You can use the TopValues property to return a specified number of records or percentage of records that meet the criteria you specify. For example, you might want to return the bottom 10 values or the top 25 percent of values in a field.

Note   The TopValue property applies only to append, make-table, and select queries.

Setting

The TopValues property setting is an Integer value representing the exact number of values to return or a number followed by a percent sign (%) representing the percentage of records to return. For example, to return the top 10 values, set the TopValues property to 10; to return the top 10 percent of values, set the TopValues property to 10 %.

You can set the TopValues property in the query property sheet.

You set this property in SQL view of the Query window by using a TOP n or TOP n PERCENT clause in the SQL statement.

You can also set the TopValues property using the Top Values combo box on the Query Design toolbar.

Note	The TopValues property in the query property sheet and on the Query Design toolbar is a combo box that contains a list of values and percentage values. You can select one of these values or you may enter any valid setting into the text box portion of this control.

Remarks

Typically, you use the TopValues property setting together with sorted fields. The field you want to display top values for should be the leftmost field that has the Sort box clicked in the query design grid. An Ascending sort returns the bottommost records, and a Descending sort returns the topmost records. If you specify that a specific number of records be returned, all records with values that match the value in the last record are also returned.

For example, suppose a set of employees have the following sales totals.

Sales	Salesperson

90,000	Leverling

80,000	Peacock

70,000	Davolio

70,000	King

60,000	Suyama

50,000	Buchanan

If you set the TopValues property to 3 with a Descending sort on the Sales field, Microsoft Access returns the following four records.

Sales	Salesperson

90,000	Leverling

80,000	Peacock

70,000	Davolio

70,000	King

Note   To return the topmost or bottommost values without displaying duplicate values, set the UniqueValues property to Yes.


TopValues Property Example

You can't set this property in code directly. It's set when you create a new query using an SQL statement. The TOP n or TOP n PERCENT clause in the SQL statement corresponds to the TopValues property setting.

This example assigns an SQL string that returns the top 10 most expensive products to the RecordSource property for a form.

Dim strGetSQL As String

strGetSQL = "SELECT DISTINCTROW TOP 10 Products.[ProductName], "

strGetSQL = strGetSQL & "AS TenMostExpensiveProducts, "

strGetSQL = strGetSQL & "Products.UnitPrice FROM Products "

strGetSQL = strGetSQL & "ORDER BY Products.[UnitPrice] DESC;"

Me.RecordSource = strGetSQL


Form, Report Properties

You can use the Form and Report properties to refer to a form or report, or refer to the form or report associated with a subform control or subreport control.

Setting

These properties refer to a form or report object. They are read-only in all views.

You can use these properties in a macro or in Visual Basic.

Remarks

These properties are typically used to refer to the form or report contained in a subform or subreport control. For example, the following code uses the Form property to access the OrderID control on a subform contained in the subOrderDetails subform control.

Dim intOrderID As Integer

intOrderID = Forms!Orders![subOrderDetails].Form![OrderID]

The next example calls a function from a property sheet using the Form property to refer to the active form that contains the control named CustomerID.

= MyFunction(Form![CustomerID])

When you use the Form property in this manner, you are referring to the active form and the name of the form isn't necessary.

The next example is the Visual Basic equivalent of the preceding example.

X = MyFunction(Forms![Customers]![CustomerID])

Note   When you use the Forms or Reports collection, you must specify the name of the form or report.


Form, Report Properties Example

The following example uses the Form and Report properties to refer to a control on a subform and a subreport.

Dim curTotalAmount As Currency

Dim curTotalSales As Currency

curTotalAmount = Forms![Orders]![OrderDetails].Form![TotalAmount]

curTotalSales = Reports![Sales]![Employees].Report![TotalSales]


LinkChildFields, LinkMasterFields Properties

You can use the LinkChildFields and LinkMasterFields properties together to specify how Microsoft Access links records in a form or report to records in a subform, subreport, or embedded object, such as a chart. If these properties are set, Microsoft Access automatically updates the related record in the subform when you change to a new record in a main form.

Setting

You can set the LinkChildFields and LinkMasterFields properties for the subform, subreport, or embedded object as follows:

LinkChildFields [image] Enter the name of one or more linking fields in the subform, subreport, or embedded object.

LinkMasterFields [image] Enter the name of one or more linking fields or controls in the main form or report.

You can use the Subform\Subreport Field Linker to set these properties by clicking the Build button to the right of the property in the property sheet.

You can also set these properties using a string expression in a macro or Visual Basic.

The properties can only be set in Design view or during the Open event of a form or report.

Remarks

The fields or controls you use to set these properties don't need to have the same names, but they must contain the same kind of data and have the same or a compatible data type and field size. For example, an AutoNumber field is compatible with a Number field if the FieldSize property for the Number field is set to Long Integer.

You can use the name of a control (including the name of a calculated control) to set the LinkMasterFields property, but you can't use the name of a control to set the LinkChildFields property. If you want to use a calculated value as the link for a subform, subreport, or embedded object, define a calculated field in the child object's underlying query and set the LinkChildFields property to the field.

When you specify more than one field or control name for these property settings, you must enter the same number of fields or controls for each property setting and separate the names with a semicolon (;).

When you create a subform or subreport by dragging a form or report from the Database window onto another form or report or by using the Form Wizard, Microsoft Access automatically sets the LinkChildFields and LinkMasterFields properties under the following conditions:

Both the main form or report and the child object are based on tables, and a relationship has been defined with the Relationships command. Microsoft Access uses the fields that relate the two tables as the linking fields.

The main form or report is based on a table with a primary key, and the subform or subreport is based on a table or query that contains a field with the same name and the same or a compatible data type as the primary key. Microsoft Access uses the primary key from the main object's underlying table and the identically named field from the child object's underlying table or query as the linking fields.

Note   The linking fields don't have to be included in the main object or in the child object. As long as they are contained in the objects' underlying tables or queries, you can use the fields to link the objects. When you use a wizard, Microsoft Access automatically includes the linking fields.


Name Property (Microsoft Access)

You can use the Name property to specify a string expression that identifies the name of a form, report, section, or control.

Setting

A valid name must start with a letter and can include numbers, underscore characters (_), or any punctuation except brackets ([ ]). Spaces are allowed in form, report, and control names. For forms and reports, the name may be up to 64 characters long. For controls, the name may be as long as 255 characters.

For forms and reports, set the Name property by clicking Save on the File menu in Design view and entering a valid name. To change the name of an existing form or report in the Database window, click the name, then either click Rename on the Edit menu or click the name again. You can also change the name by clicking it with the right mouse button and clicking Rename on the shortcut menu. To change the name of an existing form or report when the object is open, click Save As/Export on the File menu.

For a section or control, you can set this property using the property sheet, a macro, or Visual Basic. You can use the Name property in expressions for forms and reports.

You can set this property only in Design view.

Remarks

The default name for new forms and reports is the object name plus a unique Integer. For example, the first new form is Form1, the second new form is Form2, and so on. A form can't have the same name as another system object, such as the Screen object.

For an unbound control, the default name is the type of control plus a unique Integer. For example, if the first control you add to a form is a text box, its Name property setting is Text1.

For a bound control, the default name is the name of the field in the underlying source of data. If you create a control by dragging a field from the field list, the field's FieldName property setting is copied to the control's Name property box.

You can't use "Form" or "Report" to name a control or section.

Controls on the same form or report can't have the same name, but controls on different forms or reports can have the same name. A control and a section on the same form can't share the same name.


Parent Property

You can use the Parent property to refer to the parent of a control, section, or control that contains other controls. The Parent property returns a control object if the parent is a control; it returns a form object or report object if the parent is a form or report.

Setting

The Parent property refers to a form, report, or control object and is read-only in all views.

Remarks

You can use the Parent property to determine which form or report is currently the parent when you have a subform or subreport that has been inserted in multiple forms or reports.

For instance, you might insert an OrderDetail subform into both a form and a report. The following example uses the Parent property to refer to the OrderID field, which is present on the main form and report. You can enter this expression in a bound control on the subform.

= Parent![OrderID]

The Parent property of a label control is the control the label is linked to. The Parent property for a check box, option button, or toggle button in an option group is the name of the option group control. The Parent property of an option group control will be the name of the form.


Parent Property Example

The following example uses the Parent property to examine the parent of the Speedy Label label control, the Speedy check box control, and the ShipVia option group.

Dim frm As Form

Dim ctl As Control

Set frm = Forms!Orders

Set ctl = frm.[Speedy Label]

' Returns name of control attached to label.

MsgBox "The parent control is " & ctl.Parent.Name

Set ctl = frm.[Speedy]

' Returns name of control containing control.

MsgBox "The parent control is " & ctl.Parent.Name

Set ctl = frm.[ShipVia]

' Returns name of form containing option group control.

MsgBox "The parent control is " & ctl.Parent.Name

The next example also returns the name of the form containing the option group control.

MsgBox Forms!Orders[Speedy Label].Parent.Parent.Parent.Name


Section Property

You can use the Section property to identify a section of a form or report and provide access to the properties of that section. You can also identify controls by the section of a form or report where the control appears.

Setting

The Section property is an Integer data type value corresponding to a particular section.

Setting	Description

0	Form detail section or report detail section

1	Form or report header section

2	Form or report footer section

3	Form or report page header section

4	Form or report page footer section

5	Group-level 1 header section (reports only)

6	Group-level 1 footer section (reports only)

7	Group-level 2 header section (reports only)

8	Group-level 2 footer section (reports only)

If a report has additional group-level sections, the header/footer pairs are numbered consecutively beginning with 9.

The Section property is read-only in all views.

For forms and reports, the Section property is an array of all existing sections in the form or report specified by the section number. For example, Section(0) refers to a form's detail section and Section(3) refers to a form's header section.

You can also refer to a section by name. The following statements refer to the Detail0 section for the Customers form and are equivalent.

Forms![Customers].Section(0).Visible

Forms![Customers].Detail0.Visible

Remarks

For forms and reports, you must combine the Section property with other properties that apply to form or report sections. The following example shows how to refer to the Visible property of the page header section of the Customers form.

Forms![Customers].Section(3).Visible

For controls, you can use the Section property to determine which section of a form or report a control is on. The following example uses the Section property to determine which section contains the CustomerID control.

Dim intSectionNumber As Integer

intSectionNumber = Forms![Customers]![CustomerID].Section


SourceObject Property

You can use the SourceObject property to identify the form or report that is the source of the subform or subreport on a form or report. You can also use this property for linked unbound object frames to determine the complete path and filename of the file that contains the data linked to the object frame.

Setting

Enter the name of the form or report that is the source of the subform or subreport in the control's property sheet. If you add a subform or subreport to the form or report by dragging it from the Database window, the SourceObject property is set automatically in the property sheet.

For unbound object frames, the SourceObject property is set automatically when you use the Object command on the Insert menu to insert a linked OLE object.

For a subform or subreport, you can set this property using the control's property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property using a string expression that is a name of a form or report.

For linked unbound object frames, the SourceObject property can't be set in any view.

Note   You can't set or change the SourceObject property in the Open or Format events of a report.

Remarks

If you delete the SourceObject property setting in the property sheet for a subform or subreport, the control remains on the form but is no longer bound to the source form or report.


SourceObject Property Example

The following example displays the name of the form that is the source of the Product List subform control in the Debug window.

Debug.Print Forms![Categories]![Product List].SourceObject


GrpKeepTogether Property

You can use the GrpKeepTogether property to specify whether groups in a report that have their KeepTogether property (Groups) set to Whole Group or With First Detail will be kept together by page or by column.

Setting

The GrpKeepTogether property uses the following settings.

Setting	Description	Visual Basic
Per Page	Groups are kept together by page.	0
Per Column	(Default) Groups are kept together by column.	1
You can set the GrpKeepTogether property in the report's property sheet, a macro, or using Visual Basic.

This property can be set only in report Design view.

Remarks

The GrpKeepTogether property lets you specify whether all the data for a group will appear in the same column. For example, if you have a list of employees by department in a multiple-column format, you can use this property to keep all members of the same department in the same column.


HasContinued Property

You can use the HasContinued property to determine if part of the current section begins on the previous page.

Setting

The HasContinued property is set by Microsoft Access and is read-only in all views.

Value	Description

True (-1)	Part of the current section has been printed on the previous page.

False (0)	Part of the current section hasn't been printed on the previous page.

You can get the value of the HasContinued property using a macro or Visual Basic.

Remarks

You can use the HasContinued property to determine whether to show or hide certain controls depending on the value of the property. For example, you may have a hidden label in a page header containing the text "Continued from previous page". If the value of the HasContinued property is True, you can make the hidden label visible.


HasData Property

You can use the HasData property to determine if a form or report is bound to an empty recordset.

Setting

The HasData property is set by Microsoft Access. The value of this property can be read only while printing or while in Print Preview.

You can get the value of the HasData property using a macro or Visual Basic.

Value	Description

-1	The object has data.

0	The object doesn't have data.

1	The object is unbound.

Remarks

You can use the HasData property to determine whether to hide a subreport that has no data. For example, the following expression hides the subreport control when its report has no data.

Me![SubReportControl].Visible = Me![SubReportControl].Report.HasData


RepeatSection Property

You can use the RepeatSection property to specify whether a group header is repeated on the next page or column when a group spans more than one page or column.

Setting

The RepeatSection property uses the following settings.

Setting	Description	Visual Basic
Yes	The group header is repeated.	True (-1)
No	(Default) The group header isn't repeated.	False (0)
You can set the RepeatSection property in the group header section's property sheet, a macro, or using Visual Basic.

Remarks

When printing a report that contains a subreport, the subreport's RepeatSection property will determine if the subreport group headers are repeated across pages or columns.


WillContinue Property

You can use the WillContinue property to determine if the current section will continue on the following page.

Setting

The WillContinue property is set by Microsoft Access and is read-only in all views.

Value	Description

True (-1)	The current section continues on the following page.

False (0)	The current section doesn't continue on the following page.

You can get the value of the WillContinue property using a macro or Visual Basic.

Remarks

You can use the WillContinue property to determine whether to show or hide certain controls, depending on the value of the property. For example, you may have a hidden label in a page header containing the text "Continued on next page". If the value of the WillContinue property is True, you can make the hidden label visible.


ColumnWidth Property

You can use the ColumnWidth property to specify the width of a column in Datasheet view.

Note   The ColumnWidth property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You can set this property by clicking the Column Width command on the Format menu in Datasheet view and entering the desired value.

In Visual Basic, the ColumnWidth property setting is an Integer value that represents the column width in twips. You can specify a width or use one of the following predefined settings.

Setting	Description

0	Hides the column.

-1	(Default) Sizes the column to the default width.

-2	Sizes the column to fit the visible text.

Remarks

Setting the ColumnWidth property to 0, or resizing the field to a zero width in Datasheet view, sets the field's ColumnHidden property to True and hides the field in Datasheet view.

Setting a field's ColumnHidden property to False restores the field's ColumnWidth property to the value it had before the field was hidden. For example, if the ColumnWidth property was -1 prior to the field being hidden by setting its ColumnWidth property to 0, changing the field's ColumnHidden property to False resets the ColumnWidth to -1.

The ColumnWidth property for a field isn't available when the field's ColumnHidden property is set to True.


DatasheetFontItalic, DatasheetFontUnderline Properties

You can use the DatasheetFontItalic and DatasheetFontUnderline properties to specify an italic or underlined appearance for field names and data in Datasheet view.

Note   The DatasheetFontItalic and DatasheetFontUnderline properties apply to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You can set these properties by clicking the Italic or Underline button on the Datasheet Formatting toolbar.

You can also set these properties by clicking Font on the Format menu in Datasheet view.

In Visual Basic, the DatasheetFontItalic property uses the following settings.

Setting	Description

True	The text is italic.

False	(Default) The text isn't italic.

In Visual Basic, the DatasheetFontUnderline property uses the following settings.

Setting	Description

True	The text is underlined.

False	(Default) The text isn't underlined.

In Visual Basic, these properties have a data type of Boolean.


DatasheetFontItalic, DatasheetFontUnderline Properties Example

The following example displays the data and field names in Datasheet view of the Products form as italic and underlined.

Forms![Products].DatasheetFontItalic = True

Forms![Products].DatasheetFontUnderline = True

The next example displays the data and field names in Datasheet view of the Products table as italic and underlined.

To set the DatasheetFontItalic and DatasheetFontUnderline properties, the example uses the SetTableProperty procedure, which is in the database's standard module.

Dim db As Database, tdProducts As TableDef

Set db = CurrentDb

Set tdProducts = db![Products]

SetTableProperty tdProducts, "DatasheetFontItalic", dbBoolean, True

SetTableProperty tdProducts, "DatasheetFontUnderline", dbBoolean, True

Sub SetTableProperty (TableObj As TableDef, strPropertyName As String, _

intPropertyType As Integer, varPropertyValue As Variant)

' Set Microsoft Access-defined table property without causing

' nonrecoverable run-time error.

Const conErrPropertyNotFound = 3270

Dim proProperty As Property

On Error Resume Next	' Don't trap errors.

TableObj.Properties(strPropertyName) = varPropertyValue

If Err <> 0 Then	' Error occurred when value set.

If Err <> conErrPropertyNotFound Then

On Error GoTo 0

MsgBox "Couldn't set property '" & strPropertyName _

& "' on table '" & TableObj.name & "'", 48, "SetTableProperty"

Else

On Error GoTo 0

Set proProperty = TableObj.CreateProperty(strPropertyName, _

intPropertyType, varPropertyValue)

TableObj.Properties.Append proProperty

End If

End If

TableObj.Properties.Refresh

End Sub


DatasheetFontName, DatasheetFontHeight Properties

You can use the DatasheetFontName and DatasheetFontHeight properties to specify the font and the font point size used to display field names and data.

Note   The DatasheetFontName and DatasheetFontHeight properties apply to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

DatasheetFontName [image] In Visual Basic, you set this property using a string expression equal to the name of the font.

DatasheetFontHeight [image] In Visual Basic, this property setting is an Integer value between 1 and 127 representing the font height in points.

You can set these properties by choosing the font name or font height on the Datasheet Formatting toolbar.

You can also set these properties by clicking Font on the Format menu in Datasheet view.

Remarks

For the DatasheetFontName property, the font names you can specify depend on the fonts installed on your system and for your printer. If you specify a font that your system can't display or that isn't installed, Microsoft Windows will substitute a similar font.

For the DatasheetFontHeight property, the point size you specify must be valid for the font specified by the DatasheetFontName property. For example, MS Sans Serif is available in point sizes 8, 10, 12, 14, 18, and 24.


DatasheetFontName, DatasheetFontHeight, DatasheetFontWeight Properties Example

The following example sets the font to MS Serif, the point size to 10, and the font weight to medium (500) in Datasheet view of the Products table.

To set these properties, the example uses the SetTableProperty procedure, which is shown in the DatasheetFontItalic, DatasheetFontUnderline properties example.

Dim db As Database, tdProducts As TableDef

Set db = CurrentDb

Set tdProducts = db![Products]

SetTableProperty tdProducts, "DatasheetFontName", vbString, "MS Serif"

SetTableProperty tdProducts, "DatasheetFontHeight", vbInteger, 10

SetTableProperty tdProducts, "DatasheetFontWeight", vbInteger, 500

The next example makes the same changes as the preceding example in Datasheet view of the open Products form.

Forms![Products].DatasheetFontName = "MS Serif"

Forms![Products].DatasheetFontHeight = 10

Forms![Products].DatasheetFontWeight = 500


DatasheetFontWeight Property

You can use the DatasheetFontWeight property to specify the line width of the font used to display and print characters for field names and data in Datasheet view.

Note	The DatasheetFontWeight property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

In Visual Basic, the DatasheetFontWeight property setting uses the following Integer values.

Setting	Description

100	Thin

200	Extra Light

300	Light

400	(Default) Normal

500	Medium

600	Semi-bold

700	Bold

800	Extra Bold

900	Heavy

You can also set Normal and Bold for this property by clicking Font on the Format menu in Datasheet view. In the Font dialog box, the only available font weight settings are Regular (identical to Normal) and Bold.

Another method of setting only the Regular and Bold properties is to use the Datasheet Formatting toolbar.


FrozenColumns Property

You can use the FrozenColumns property to determine how many columns in a datasheet are frozen. Frozen columns are displayed on the left side of the datasheet and don't move when you scroll horizontally through the datasheet.

Note	The FrozenColumns property applies only to tables, forms, and queries in Datasheet view.

Setting

The FrozenColumns property is set by Microsoft Access when you click Freeze Columns on the Format menu.

In Visual Basic, this property setting is an Integer indicating the number of columns in the datasheet that have been frozen using the Freeze Columns command. The record selector column is always frozen, so the default value is 1. Consequently, if you freeze one column, the FrozenColumns property is set to 2; if you freeze two columns, it's set to 3; and so on.

This property setting is read-only in all views.

Remarks

When you freeze columns using the Freeze Columns command, Microsoft Access automatically moves the columns to the leftmost edge of the datasheet in the order in which you froze them. For example, if you freeze three columns, these become the first, second, and third columns in the datasheet. Because the record selector column is always frozen, the FrozenColumns property in this case will be set to 4. The three columns you freeze will have their ColumnOrder properties set to 1, 2, and 3 (in the order they are frozen).

If you click Unfreeze All Columns on the Format menu, all frozen columns will be unfrozen, and the FrozenColumns property will be set to 1.


FrozenColumns Property Example

The following example uses the FrozenColumns property to determine how many columns are frozen in a table in Datasheet view. If more than three columns are frozen, the table size is maximized so you can see as many unfrozen columns as possible.

Sub CheckFrozen(tblName As String)

Dim db As Database

Dim td As TableDef

Dim prop As Property

conPropertyNotFound = 3270	' Property not found error.

Set db = CurrentDb	' Get current database.

Set td = db.TableDefs(tblName)	' Get object for table.

DoCmd.OpenTable tblName, acNormal	' Open table.

td.Properties.Refresh

On Error GoTo Frozen_Err

If td.Properties("FrozenColumns") > 3 Then	 ' Check property.

DoCmd.Maximize

End If

Frozen_Bye:

Exit Sub

Frozen_Err:

If Err = conPropertyNotFound Then	' Property not in collection

Set prop = td.CreateProperty("FrozenColumns", dbInteger, 1)

td.Properties.Append prop

Resume Frozen_Bye

End If

End Sub


RowHeight Property

You can use the RowHeight property to specify the height of all rows in Datasheet view.

Note	The RowHeight property applies to all fields in Datasheet view and to form controls when the form is in Datasheet view.

Setting

You set the RowHeight property in Datasheet view by dragging the lower border of the record selector or by clicking the Row Height command on the Format menu. When you set the RowHeight property using the Row Height command, the value is expressed in points.

In Visual Basic, the RowHeight property setting is a Long value that represents the datasheet row height in twips. To specify the default height for the current font, you can set the RowHeight property to True (-1).


RowHeight, ColumnWidth Properties Example

The following example changes the row height in Datasheet view of the Customers table to display two lines of data (450 twips) and sets the width of the Address column to 1.5 inches (2160 twips). These property settings will take effect the next time the Customers table is opened in Datasheet view.

To set the RowHeight and ColumnWidth properties, the example uses the SetTableProperty procedure, which is shown in the example for the DatasheetFontItalic and DatasheetFontUnderline properties, and the SetFieldProperty procedure, which is shown in the example for the ColumnHidden property.

Dim db As Database, tdCustomers As TableDef

Set db = CurrentDb

Set tdCustomers = db![Customers]

SetTableProperty tdCustomers, "RowHeight", dbLong, 450

SetFieldProperty tdCustomers![Address], "ColumnWidth", dbInteger, 2160

The next example takes effect in Datasheet view of the open Customers form. It sets the row height to 450 twips and sizes the column to fit the size of the visible text.

Forms![Customers].RowHeight = 450

Forms![Customers]![Address].ColumnWidth = -2


ShowGrid Property

You can use the ShowGrid property to specify whether grid lines are visible when the table, query, or form is displayed in Datasheet view.

Note   The ShowGrid property is included in this version of Microsoft Access only for compatibility with previous versions. It is recommended that you use the DatasheetGridLinesBehavior property instead.

The ShowGrid property applies to all fields in Datasheet view.

Setting

The ShowGrid property uses the following settings.

Setting	Description	Visual Basic
True	The display grid lines are displayed in Datasheet view	True (-1)
False	The grid lines aren't displayed in Datasheet view.	False (0)
In previous versions of Microsoft Access, you could set the ShowGrid property in Datasheet view by clicking Gridlines on the Format menu.


CanGrow, CanShrink Properties

You can use the CanGrow and CanShrink properties to control the appearance of sections on reports and controls on forms that are printed. For example, if you set both properties to Yes, a section or control automatically adjusts vertically to print or display all the data the report or form contains.

Note	The CanGrow and CanShrink properties do not apply to form or report header and footer sections.

Setting

The CanGrow property uses the following settings.

Setting	Description	Visual Basic
Yes	The section or control grows vertically so that Microsoft Access can print all the data it contains.	True (-1)
No	(Default) The section or control doesn't grow. Data that can't be seen won't be printed.	False (0)
The CanShrink property uses the following settings.

Setting	Description	Visual Basic
Yes	The section or control shrinks vertically so that Microsoft Access can print the data it contains without leaving blank lines.	True
No	(Default) The section or control doesn't shrink.	False
You can set these properties only in the property sheet.

For controls, you can set the default for these properties using the default control style.

These property settings are read-only in Visual Basic.

Remarks

If you set a control's CanGrow property to Yes, Microsoft Access automatically sets the CanGrow property of the section containing the control to Yes.

Sections grow and shrink vertically across their entire width. However, report header and footer sections will not grow, even if the CanGrow property of a control is set to Yes.

When you use the CanGrow and CanShrink properties, remember that:

The property settings don't affect the horizontal spacing between controls; they affect only the vertical space the controls themselves occupy.

Overlapping controls can't grow or shrink.

The size of a large control can prevent controls beside it from shrinking. For example, if several small controls are on the left side of a report's detail section and one large control, such as an unbound object frame, is on the right side, the controls on the left will not shrink, even if they contain no data.


Height, Width Properties

You can use the Height and Width properties to size an object to specific dimensions. This can be useful, for example, if you want to create objects that are exactly the same size or that have the same width or height.

Setting

Enter a number for the desired height or width in the current unit of measurement. To use a unit of measurement different from the setting in the Regional Settings section of the Windows Control Panel, specify the unit, such as cm or in (for example, 5 cm or 3 in).

You can set these properties using the object's property sheet, a macro, or Visual Basic.

For controls, you can set the default for these properties using the default control style.

In Visual Basic, use a numeric expression to set the value of each property. Values are expressed in twips.

You can't set these properties for an object once the print process has started. For example, attempting to set the Height property in a report's OnPrint event generates an error.

Remarks

Microsoft Access automatically sets the Height and Width properties when you create or size a control or when you size a window in form or report Design view.

The height and width of forms and reports are measured from the inside of their borders. The height and width of controls are measured from the center of their borders so controls with different border widths align correctly. The margins for forms and reports are set in the Page Setup dialog box.

Note   To set the left and top location of an object, use the Left and Top properties.


Height, Width Properties Example

The following code resizes a command button to a 1-inch by 1-inch square button (and assumes the default unit of measure is set to twips).

Me!cmdSizeButton.Height = 1440	' 1440 twips = 1 inch.

Me!cmdSizeButton.Width = 1440


Height, Width Properties - Applies To
Height, Width Properties — Applies To

Height Property

Width Property


LabelX, LabelY Properties

You can use the LabelX and LabelY properties to change the placement of labels attached to new controls. For example, you might want an attached label to appear to the right of a control instead of to the left.

Setting

Enter a positive or negative number that specifies the distance of label text from the upper-left corner of the label's attached control. To use a unit of measurement different from the setting in the Regional Settings section of the Windows Control Panel, specify the unit, such as cm or in (for example, 2 cm or 1.5 in).

You can set the default for these properties using a control's default control style.

Remarks

The LabelX property sets the distance on the horizontal axis and the LabelY property sets the distance on the vertical axis. A negative number for the LabelX property places the label's upper-left corner to the left of the control. A negative number for the LabelY property places the label's upper-left corner above the control. Positive numbers for both properties place the label to the right and below the upper-left corner of the control.

If the LabelAlign property is set to Right or Left, the LabelX and LabelY properties specify the distance between the right or left edge of the label and the control's upper-left corner. If the LabelAlign property is set to Center, the LabelX and LabelY properties specify the distance between the center of the label and the control's upper-left corner.

Combining the LabelX, LabelY, and LabelAlign properties produces the following results.

LabelX	LabelY	LabelAlign	Result
-1 in	0 in	General	The label's upper-left corner is 1 inch to the left of the control's upper-left corner.
-.5 in	0 in	Right	The label's upper-right corner is 0.5 inch to the left of the control's upper-left corner.
.5 in	-.5 in	Center	The center of the top of the label is 0.5 inch to the right and 0.5 inch above the control's upper-left corner.


Left, Top Properties

You can use the Left and Top properties to specify an object's location on a form or report. For example, you might want a control to be always aligned at the upper-right corner of a section.

Setting

A control's location is the distance measured from its left or top border to the left or top edge of the section containing the control. Setting the Left or Top property to 0 places the control's edge at the very left or top of the section. To use a unit of measurement different from the setting in the Regional Settings section of the Windows Control Panel, specify the unit, such as cm or in (for example, 3 cm or 2 in).

In Visual Basic, use a numeric expression to set the value of this property. Values are expressed in twips.

For controls, you can set these properties using control's property sheet, a macro, or Visual Basic.

For reports, you can set these properties only in an event procedure while the report is in the Print Preview window or being printed.

Remarks

When you move a control, its new Left and Top property settings are automatically entered in the property sheet. When you view a form or report in Print Preview or when you print a form, a control's location is determined by its Left and Top property settings along with the margin settings in the Print Setup dialog box.

For reports, the Top property setting is the amount the current section is offset from the top of the page; the Left property setting is the amount the current section is offset from the left edge of the page. Both property settings are expressed in twips. You can use these properties to specify how far down the page you want a section to print in the section's Format event procedure.

Note   To set the bottom and right margins, use the Height and Width properties.


Left, Top Properties Example

The following example checks the Left property setting for the current report. If the value is less than the minimum margin setting, the intNextRecord and intPrintSection variables are set to False (0).

Sub Detail1_Format(Cancel As Integer, FormatCount As Integer)

Const conLeftMargin = 1880
Dim intNextRecord As Integer, intPrintSection As Integer

' Don't advance to next record or print next section

' if Left property setting is more than 1880 twips.

If Me.Left < conLeftMargin Then

intNextRecord = False

intPrintSection = False

End If

End Sub


ControlSource Property

You can use the ControlSource property to specify what data appears in a control. You can display and edit data bound to a field in a table, query, or SQL statement. You can also display the result of an expression. For a report group level, the ControlSource property determines the field or expression to group on.

Note   The ControlSource property doesn't apply to check box, option button, or toggle button controls in an option group. It applies only to the option group itself.

For reports, the ControlSource property applies only to report group levels.

Setting

The ControlSource property has the following settings.

Setting	Description

A field name	The control is bound to a field in a table, query, or SQL statement. Data from the field is displayed in the control. Changes to the data inside the control change the corresponding data in the field. (To make the control read-only, set the Locked property to Yes.)

An expression	The expression generates data for the control. This data is read-only and is not saved in the database.

You can set the ControlSource property for a control using the control's property sheet, a macro, or Visual Basic. You can also set the ControlSource property for a text box by typing a field name or expression directly in the text box in form or report Design view.

For a report, you can set this property by selecting a field or typing an expression in the Field/Expression column of the Sorting And Grouping box. For details, see the GroupLevel property.

In Visual Basic, use a string expression to set the value of this property.

Remarks

Forms and reports act as "windows" into your database. You specify the primary source of data for a form or report by setting its RecordSource property to a table, query, or SQL statement. You can then set the ControlSource property to a field in the source of data or to an expression. If the ControlSource property setting is an expression, the value displayed is read-only and not saved in the database. For example:

Example Setting	Description

LastName	A field name in the source specified by the RecordSource property of a form or report. For a control, data from the LastName field is displayed in the control. For a report group level, Microsoft Access groups the data on last name.

= Date( ) + 7	An expression. For a control, this expression displays a date seven days from today in the control.

= DatePart("q",[ShippedDate])	An expression. For a control, this expression displays the quarter of the shipped date. For a report group level, Microsoft Access groups the data on the quarter of the shipped date.


ControlSource Property Example

The following example sets the ControlSource property for a text box named AddressPart to a field named City.

Forms![Customers]![AddressPart].ControlSource = "City"

The next example sets the ControlSource property for a text box named Expected to the expression = Date() + 7.

Forms![Invoice]![Expected].ControlSource = "= Date() + 7"


OptionValue Property

Each control in an option group has a numeric value that you can set with the OptionValue property. When the control is selected, the number is assigned to the option group. If the option group is bound to a field, the value of the selected control's OptionValue property is stored in the field.

For example, this Region option group is bound to the Region field in a table. The Europe button has an OptionValue property setting of 1, the Asia button has a setting of 2, and the Africa button has a setting of 3. When one of these buttons is selected, the Region option group value will be the same as the OptionValue property setting for the selected control. In this case, because the Region option group is bound to the Region field, the value of this field in the table also equals 2.

Note   The OptionValue property applies only to the check box, option button, and toggle button controls in an option group.

Setting

The OptionValue property holds a Long Integer or numeric expression assigned to a control within an option group control.

You can set the OptionValue property by using the control's property sheet, a macro, or Visual Basic.

Remarks

Unless you change the OptionValue property yourself, the first control you place in an option group has a value of 1, the second control has a value of 2, and so on.

The OptionValue property is only available when the control is placed inside an option group control. When a toggle button, an option button, or a check box is not in an option group, the control has no OptionValue property. Instead, each such control has a ControlSource property and the value of each control will be either True (-1) if selected, or False (0) if not selected.


RecordSource Property

You can use the RecordSource property to specify the source of the data for a form or report. You can display data from a table, query, or SQL statement. For example, to display and edit data from the Employees table in a form, you set the form's RecordSource property to Employees. Then you can bind controls on the form or report to specific fields in the Employees table by setting the control's ControlSource property to the name of a field in the table.

Setting

The RecordSource property setting can be a table name, a query name, or an SQL statement. For example, you can use the following settings.

Sample Setting	Description

A table or query name	You can bind a control on the form or report to the LastName field in the Employees table by setting the control's ControlSource property to LastName.

An SQL statement	You can bind a control on the form or report to the OrderDate field in the Orders table by setting the control's ControlSource property to OrderDate, as in the following example.

SELECT DISTINCTROW Orders.[OrderDate] FROM Orders;

You can set the RecordSource property using the form or report's property sheet, a macro, or Visual Basic.

In Visual Basic, use a string expression to set this property.

Note   Changing the record source of an open form or report causes an automatic requery of the underlying data.

Remarks

After you have created a form or report, you can change its source of data by changing the RecordSource property. The RecordSource property is also useful if you want to create a reusable form or report. For example, you could create a form that incorporates a standard design, then copy the form and change the RecordSource property to display data from a different table, query, or SQL statement.

Limiting the number of records contained in a form's record source can enhance performance, especially when your application is running on a network. For example, you can set a form's RecordSource property to a single record and change the form's record source depending on criteria selected by the user.

You can also achieve improved performance by setting the RecordSource property to the name of a table or saved query instead of an SQL statement.


RecordSource Property Example

The following example sets the RecordSource property for a form to the Customers table.

Forms![frmCustomers].RecordSource = "Customers"

The next example changes a form's record source to a single record in the Customers table, depending on the company name selected in the cmboCompanyName combo box control. The combo box is filled by an SQL statement that returns the customer ID in the bound column and the company name.

Sub cmboCompanyName_AfterUpdate()

Dim strNewRecord As String

strNewRecord = "SELECT DISTINCTROW * FROM Customers "

strNewRecord = strNewRecord & "WHERE [CustomerID] = '" _

& Me!cmboCompanyName.Value & "'"

Me.RecordSource = strNewRecord

End Sub


RowSourceType, RowSource Properties

You can use the RowSourceType and RowSource properties together to tell Microsoft Access how to provide data to a list box, a combo box, or an unbound OLE object such as a chart. For example, to display rows of data in a list box from a query named CustomerList, set the list box's RowSourceType property to Table/Query and its RowSource property to the query named CustomerList.

Setting

The RowSourceType property has the following settings.

Setting	Description

Table/Query	(Default) The data is from a table, query, or SQL statement specified by the RowSource setting.

Value List	The data is a list of items specified by the RowSource setting.

Field List	The data is a list of field names from a table, query, or SQL statement specified by the RowSource setting.

Note   You can also set the RowSourceType property with a user-defined function. In this case the data is an array of values defined by the user. The function name is entered without a preceding equal sign (=) and without the trailing pair of parentheses. You must provide specific function code arguments to tell Microsoft Access how to fill the control.

The RowSource property setting depends on the RowSourceType property setting.

For this RowSourceType	Enter this RowSource

Table/Query	Enter a table name, a query name, or an SQL statement.

Value List	Enter a list of items using semicolons (;) as separators.

Field List	Enter a table name, a query name, or an SQL statement.

Note   If the RowSourceType property is set to a user-defined function, the RowSource property must be left blank.

You can set the RowSourceType and RowSource properties using the control's property sheet, a macro, or Visual Basic.

For table fields, you can set these properties in table Design view for fields with the DisplayControl property set to combo box or list box.

Note   Microsoft Access sets these properties automatically when you select Lookup Wizard as the data type for a field in table Design view.

In Visual Basic, set the RowSourceType property using a string expression with one of these values: "Table/Query", "Value List", or "Field List". You also use a string expression to set the value of the RowSource property. To set the RowSourceType property to a user-defined function, enter the name of the function.

Remarks

When you have a limited number of values that do not change, you can set the RowSourceType property to Value List and then enter the values that make up the list in the RowSource property.

When you create a user-defined function to insert items into a list box or combo box, Microsoft Access calls the function repeatedly to get the information it needs. User-defined RowSourceType functions must be written in a very specific function format.


RowSourceType, RowSource Properties Examples - Settings
RowSourceType, RowSource Properties Examples — Settings

The following examples show sample RowSource property settings for each RowSourceType property setting.

When RowSourceType is set to Value List

If the RowSourceType property is set to Value List, the following table shows valid settings for the RowSource and ColumnCount properties and an illustration of the resulting list.

RowSource setting	List
Mon;Tue;Wed (ColumnCount = 1)	One-column list with three rows
1;Monday;2;Tuesday;3;Wednesday;4;Thursday (ColumnCount = 2)	Two-column list with four rows
Country;Capital;China;Beijing;Brazil;Brasilia (ColumnCount = 2, ColumnHeads = Yes)	Two-column list with one row of column heads and two rows of data
When RowSourceType is set to Table/Query

If the RowSourceType property is set to Table/Query, you can set the RowSource property to a table or query name [image] for example, CategoryList.

The following is a valid SQL statement for a two-column list drawn from the Categories table.

SELECT [CategoryID], [CategoryName] FROM [Categories] ORDER BY [CategoryName];

If the CategoryList query and the SQL statement define the same set of records, the list for either property setting looks like the following illustration.

When RowSourceType is set to Field List

If the RowSourceType property is set to Field List and the RowSource property to CustomerList (the query described in the previous example), the resulting list looks like the following illustration.

When RowSourceType is set to User-Defined

If the RowSourceType property is set to the name of a user-defined function, then the RowSource property setting must be left blank. For example, a user-defined function named ListMDBs that fills a combo box with the names of all the databases in the current directory is entered in the property sheet like the following illustration.


RowSourceType, RowSource Properties Example - Visual Basic
RowSourceType, RowSource Properties Example — Visual Basic

The following example sets the RowSourceType property for a combo box to Table/Query, and it sets the RowSource property to a query named EmployeeList.

Forms![frmEmployees]![cmboNames].RowSourceType = "Table/Query"

Forms![frmEmployees]![cmboNames].RowSource = "EmployeeList"


RowSourceType (User-Defined Function) - Code Argument Values
RowSourceType (User-Defined Function) — Code Argument Values

The Visual Basic function you create must accept five arguments. The first argument must be declared as a control and the remaining arguments as Variants. The function itself must return a Variant.

Syntax

Function functionname(fld As Control, id As Variant, row As Variant, col As Variant, code As Variant) As Variant

The following are the five required arguments.

Argument	Description

fld	A control variable that refers to the list box or combo box being filled.

id	A unique value that identifies the control being filled; this is useful when you want to use the same user-defined function for more than one list box or combo box and must distinguish between them. (The example sets this variable to the value of the Timer function.)

row	The row being filled (zero-based).

col	The column being filled (zero-based).

code	A value that specifies the kind of information being requested.

Note   Because Microsoft Access calls a list function several times to insert items into a list, often you must preserve information from call to call. The best way to do this is to use Static variables.

Microsoft Access calls the user-defined function repeatedly using different values in the code argument to specify the information it needs. The code argument can have the following values.

Code	Meaning	Function returns
0	Initialize	Nonzero if the function can fill the list; False or Null otherwise.
1	Open	Nonzero ID value if the function can fill the list; False or Null otherwise.
2	(Not used)
3	Number of rows	Number of rows in the list (can be zero); -1 if unknown.
4	Number of columns	Number of columns in the list (can't be zero); must match the property sheet value.
5	Column width	Width (in twips) of the column specified by the col argument; or -1 to use the default width.
6	List entry	List entry to be displayed in the row and column specified by the row and col arguments.
7	Format string	Format string to be used to format the list entry displayed in the row and column specified by the row and col arguments; or Null to use the default format.
8	(Not used)
9	End (the last call to a list function always uses this value)	Nothing.
Microsoft Access calls your list function once for codes 0, 1, 3, and 4. It initializes the list function, opens the query, and determines the number of rows and columns.

Microsoft Access calls your list function twice for code 5 [image] once to determine the total width of the list box or combo box and a second time to set the column width.

The number of times your list function is called for codes 6 and 7 to get list entries and to format strings varies depending on the number of entries, the user's scrolling, and other factors.

Microsoft Access calls the list function for code 9 when the form is closed or each time the list box or combo box is queried.

Whenever a particular value (such as the number of columns) is required, returning Null or any invalid value causes Microsoft Access to stop calling the list function with that code.

Tip   You can use the Select Case code structure from the example as a template for your own RowSourceType user-defined functions.

Your user-defined function can use the numeric codes or the corresponding constants. Intrinsic constants have several advantages. They don't have to be loaded or declared, and they're more descriptive than the numeric codes. The following table lists the numeric codes and their corresponding intrinsic constants.

Code	Intrinsic Constant

0	acLBInitialize

1	acLBOpen

3	acLBGetRowCount

4	acLBGetColumnCount

5	acLBGetColumnWidth

6	acLBGetValue

7	acLBGetFormat

8	acLBClose

9	acLBEnd

Note   You can't create your own constants with the same names as Microsoft Access intrinsic constants.


RowSourceType (User-Defined Function) - Code Argument Values Example
RowSourceType (User-Defined Function) — Code Argument Values Example

The following user-defined function returns a list of the next four Mondays following today's date. To call this function from a list box control, enter ListMondays as the RowSourceType property setting and leave the RowSource property setting blank.

Function ListMondays(fld As Control,id As Variant,row As Variant,col As Variant,code As Variant) As Variant

Dim intOffset As Integer

Select Case code

Case 0	' Initialize.

ListMondays = True

Case 1	' Open.

ListMondays = Timer	' Generate unique ID for control.

Case 3	' Get number of rows.

ListMondays = 4

Case 4	' Get number of columns.

ListMondays = 1

Case 5	' Get column width.

ListMondays = -1	' -1 forces use of default width.

Case 6	' Get the data.

intOffset = Abs((9 - Weekday(Now))Mod 7)

ListMondays = Format(Now() + intOffset + 7 * row,"mmmm d")

End Select

End Function

The following example uses a static array to store the names of the databases in the current directory. To call this function, enter ListMDBs as the RowSourceType property setting and leave the RowSource property setting blank.

Function ListMDBs (fld As Control, id As Variant, row As Variant, col As Variant, code As Variant) As Variant

Static dbs(127), Entries

Dim ReturnVal

ReturnVal = Null

Select Case code

Case LB_INITIALIZE	' Initialize.

Entries = 0

dbs(Entries ) = Dir("*.MDB")

Do Until dbs(Entries) = "" Or Entries >= 127

Entries = Entries+1

dbs(Entries) = Dir

Loop

ReturnVal = Entries

Case LB_OPEN	' Open.

ReturnVal = Timer	' Generate unique ID for control.

Case LB_GETROWCOUNT	' Get number of rows.

ReturnVal = Entries

Case LB_GETCOLUMNCOUNT	' Get number of columns.

ReturnVal = 1

Case LB_GETCOLUMNWIDTH	' Column width.

ReturnVal = -1	' -1 forces use of default width.

Case LB_GETVALUE	' Get data.

ReturnVal = dbs(row)

Case LB_END	' End.

For Entries = 0 to 127

dbs(Entries) = ""

Next

End Select

ListMDBs = ReturnVal

End Function


RunningSum Property

You can use the RunningSum property to calculate record-by-record or group-by-group totals in a report. The RunningSum property specifies whether a text box on a report displays a running total and lets you set the range over which values are accumulated. For example, if you group data by month and show the sum of each month's sales in the group footer. You can show the running sum of accumulated sales over the entire report (sales for January in the January footer, sales for January plus February in the February footer, and so on) by adding a text box to the footer that shows the sum of sales and setting its RunningSum property to Over All.

Note   The RunningSum property applies only to a text box on a report.

Setting

The RunningSum property has the following settings.

Setting	Description	Visual Basic
No	(Default) The text box displays the data from the underlying field for the current record.	0
Over Group	The text box displays a running sum of values in the same group level. The value accumulates until another group level section is encountered.	1
Over All	The text box displays a running sum of values in the same group level. The value accumulates until the end of the report.	2
You can set the RunningSum property using the text box's property sheet, a macro, or Visual Basic. You can set the RunningSum property only in Design view.

Remarks

Place the text box in the detail section to calculate a record-by-record total. For example, to number the records appearing in a detail section of a report, set the ControlSource property for the text box to 1, and set the RunningSum property to Over Group.

Place the text box in a group header or group footer to calculate a group-by-group total.

You can have up to 10 nested group levels in a report.


RunningSum Property Example - Sales Report
RunningSum Property Example — Sales Report

The following example shows a sales report with two group levels [image] Month and Type of Food. Each text box in the Type of Food group footer (January Chocolates, January Meat, and so on) contains the following expression:

= Sum([Sales])

The RunningSum property of each text box is set to one of the three different values: No, Over Group, and Over All.

Group levels	No	Over Group	Over All

Month: January

Type of Food: Chocolates

02-Jan	25
22-Jan	75
January Chocolates	100	Jan Food 100		YTD Sales 100

Type of Food: Meat

03-Jan	90
20-Jan	60
January Meat	150	Jan Food 250		YTD Sales 250

Month: February

Type of Food: Chocolates
05-Feb	70
19-Feb	80
February Chocolates	150	Feb Food 150	YTD Sales 400

Type of Food: Meat

12-Feb	150
22-Feb	100
February Meat	250	Feb Food 400	YTD Sales 650


RunningSum Property Example - Visual Basic
RunningSum Property Example — Visual Basic

The following example sets the RunningSum property for a text box named SalesTotal to 2 (Over All).

Reports![rptSales]![SalesTotal].RunningSum = 2


AllowZeroLength Property (Microsoft Access)

You can use the AllowZeroLength property to specify whether a zero-length string (" ") is a valid entry in a field.

Note   The AllowZeroLength property applies only to text and Memo table fields.

Setting

The AllowZeroLength property uses the following settings.

Setting	Description	Visual Basic
Yes	A zero-length string is a valid entry.	True (-1)
No	(Default) A zero-length string is an invalid entry.	False (0)
You can set this property in the table's property sheet or Visual Basic.

Note   To access a field's AllowZeroLength property using Visual Basic, use the Data Access Object's AllowZeroLength property.

Remarks

You can use the settings of the AllowZeroLength and Required properties to differentiate between information that doesn't exist (stored as a zero-length string in the field) and information that may exist but is unknown (stored as a Null value in the field). For example, you might have customers in your database who don't have a fax number. If the AllowZeroLength property is set to Yes and the Required property is set to No, you can enter a zero-length string to indicate that a customer doesn't have a fax number. If you leave the Fax field blank (you don't type a number or you delete the existing number), it can indicate that the customer may have a fax number, but you don't know what it is.

Note   You need to use an input mask when data is entered in a field to distinguish between the display of a Null value and a zero-length string. For example, the string "None" can be displayed when a zero-length string is entered.

The AllowZeroLength property works independently of the Required property. The Required property determines only whether a Null value is valid for the field. If the AllowZeroLength property is set to Yes, then a zero-length string will be a valid value for the field regardless of the setting of the Required property.

The following table shows the results of combining the settings of the AllowZeroLength and Required properties.

AllowZeroLength	Required	User's action	Value stored
No	No	Presses ENTER Presses SPACEBAR Enters a zero-length string	Null Null (not allowed)
Yes	No	Presses ENTER Presses SPACEBAR Enters a zero-length string	Null Null Zero-length string
No	Yes	Presses ENTER Presses SPACEBAR Enters a zero-length string	(not allowed) (not allowed) (not allowed)
Yes	Yes	Presses ENTER Presses SPACEBAR Enters a zero-length string	(not allowed) Zero-length string Zero-length string


Caption Property

You can use the Caption property to provide helpful information to the user through captions on objects in various views:

Fields [image] Specifies the text for labels attached to controls created by dragging a field from the field list and serves as the column heading for the field in table or query Datasheet view.

Forms [image] Specifies the text that appears in the title bar in Form view.

Reports [image] Specifies the title of the report in Print Preview.

Buttons and labels [image] Specifies the text that appears in the control.

Setting

Enter the caption text. Captions can have up to 2,048 characters. Captions for forms and reports that are too long to display on the title bar are truncated.

For controls, you can set this property in the property sheet. For fields, you can set this property in the property sheet in table Design view or in the Query window (in the Field Properties property sheet). You can also use a macro or Visual Basic. In Visual Basic, use a string expression to set the value of this property for forms, reports, and controls.

Remarks

If you don't specify a caption for a table field, the field's FieldName property setting will be used as the caption of a control or as the column heading. If you don't specify the caption for a query field, the one for the underlying table field will be used. If you don't set a caption for a form, button, or label, Microsoft Access will assign the object a unique name based on the object, such as "Form1". If you create a control by dragging a field from the field list and haven't specified a Caption property setting for the field, the field's FieldName property setting will be copied to the control's Name property box and will also appear in the label of the control created.

You can use the Caption property to assign an access key to a control. In the caption, include an ampersand (&) immediately preceding the character you want for an access key. The character will be underlined. When browsing the form, press ALT plus the underlined character to move the focus to that control.

Tip   Include two ampersands (&&) in the setting for a control's caption if you want to display an ampersand itself in the caption text. For example, to display "Save & Exit", you should type Save && Exit in the Caption property box.


DataType Property

You can use the DataType property to specify the type of data stored in a table field. Each field can store data only of a single data type.

Setting

The DataType property uses the following settings.

Setting	Type of data	Size
Text	(Default) Text or combinations of text and numbers, as well as numbers that don't require calculations, such as phone numbers.	Up to 255 characters or the length set by the FieldSize property, whichever is less. Microsoft Access does not reserve space for unused portions of a text field.
Memo	Lengthy text or combinations of text and numbers.	Up to 64,000 characters.
Number	Numeric data used in mathematical calculations. For more information on how to set the specific Number type, see the FieldSize property topic.	1, 2, 4, or 8 bytes (16 bytes for ReplicationID only).
Date/Time	Date and time values for the years 100 through 9999.	8 bytes.
Currency	Currency values and numeric data used in mathematical calculations involving data with one to four decimal places. Accurate to 15 digits on the left side of the decimal separator.	8 bytes.
AutoNumber	A unique sequential (incremented by 1) number or random number assigned by Microsoft Access whenever a new record is added to a table. AutoNumber fields can't be updated. For more information, see the NewValues property topic.	4 bytes (16 bytes for ReplicationID only).
Yes/No	Yes and No values and fields that contain only one of two values (True/False, On/Off).	1 bit.
OLE Object	An object (such as a Microsoft Excel spreadsheet, a Microsoft Word document, graphics, sounds, or other binary data) linked to or embedded in a Microsoft Access table.	Up to 1 gigabyte (limited by available disk space)
Lookup Wizard...	Creates a field that allows you to choose a value from another table or from a list of values using a combo box. Choosing this option in the Data Type list starts the Lookup Wizard to define the data type.	The same size as the primary key field used to perform the lookup, typically 4 bytes.
You can set this property only in the upper portion of table Design view.

In Visual Basic, use the Data Access Objects Type property to read and set an object's data type.

Remarks

Memo fields and OLE Object fields can't be indexed.

Tip   Use the Currency data type for a field requiring many calculations involving data with one to four decimal places. Single and Double data type fields require floating-point calculation. The Currency data type uses a faster fixed-point calculation.

Caution   Changing a field's data type after you enter data in a table causes a potentially lengthy process of data conversion when you save the table. If the data type in a field conflicts with a changed DataType property setting, you may lose some data.

Set the Format property to specify a custom or one of the predefined display formats for Number, Date/Time, Currency, and Yes/No data types.


DecimalPlaces Property

You can use the DecimalPlaces property to specify the number of decimal places Microsoft Access uses to display numbers.

Setting

The DecimalPlaces property uses the following settings.

Setting	Description	Visual Basic
Auto	(Default) Numbers appear as specified by the Format property setting.	255
0 to 15	Digits to the right of the decimal separator appear with the specified number of decimal places; digits to the left of the decimal separator appear as specified by the Format property setting.	0 to 15
You can set this property for text boxes and combo boxes in the control's property sheet, for table fields in the table's property sheet.

For controls, you can also set this property using a macro or Visual Basic.

Note   The DecimalPlaces property setting has no effect if the Format property is blank or is set to General Number.

Remarks

The DecimalPlaces property affects only the number of decimal places that display, not how many decimal places are stored. To change the way a number is stored you must change the FieldSize property.

You can use the DecimalPlaces property to display numbers differently from the Format property setting or from the way they are stored. For example, the Currency setting of the Format property displays only two decimal places ($5.35). To display Currency numbers with four decimal places (for example, $5.3523), set the DecimalPlaces property to 4.

Tip   You should set the DecimalPlaces property in the table's property sheet. A bound control you create on a form or report inherits the DecimalPlaces property set in the field in the underlying table or query, so you won't have to specify the property individually for every bound control you create.


Description Property (Microsoft Access)

You can use the Description property to provide information about objects contained in the database window as well as about individual table or query fields.

Setting

For a database object, choose the Properties command from the View menu and enter the description text in the Description box. For tables or queries, you can also enter the description in the table’s or query’s property sheet. An object's description appears next to the object's name in the database window

For individual table or query fields, enter the field description in the upper portion of table Design view, or in the Query window. The maximum length is 255 characters.

In Visual Basic, to set this property for the first time you must create an application-defined property using the CreateProperty method.

Remarks

An object’s description is displayed in the Description column in Database window Details view by clicking Details View on the View menu.

If you create controls by dragging a field from the field list, Microsoft Access copies the field's Description property to the control's StatusBarText property.

Note   For a linked table, Microsoft Access displays the connection information in the Description property.


FieldSize Property

You can use the FieldSize property to set the maximum size of data that can be stored in a field set to Text or Number data type.

Setting

If the DataType property is set to Text, enter a number from 0 to 255. The default setting is 50.

If the DataType property is set to Number, the FieldSize property settings and their values are related in the following way.

Setting	Description	Decimal precision	Storage Size
Byte	Stores numbers from 0 to 255 (no fractions).	None	1 byte
Integer	Stores numbers from -32,768 to 32,767 (no fractions).	None	2 bytes
Long Integer	(Default) Stores numbers from -2,147,483,648 to 2,147,483,647 (no fractions).	None	4 bytes
Single	Stores numbers from  -3.402823E38 to 3.402823E38.	7	4 bytes
Double	Stores numbers from  -1.79769313486232E308 to 1.79769313486232E308.	15	8 bytes
ReplicationID	Globally Unique Identifier (GUID)	N/A	16 bytes
You can set this property in the table's property sheet or using Visual Basic.

In Visual Basic, use the Data Access Object's Size property to read and set the maximum size of text fields (for data types other than Text, the Type property setting automatically determines the Size property setting).

Note   You can specify the default field sizes for text and number fields by changing the values under the Default Field Sizes option on the Tables/Queries tab, available by clicking Options on the Tools menu.

Remarks

You should use the smallest possible FieldSize property setting because smaller data sizes can be processed faster and require less memory.

Caution   If you convert a large FieldSize setting to a smaller one in a field that already contains data, you might lose data in the field. For example, if you change the FieldSize setting for a Text data type field from 255 to 50, data beyond the 50 characters will be discarded.

If the data in a Number data type field doesn't fit in a new FieldSize setting, fractional numbers may be rounded or you might get a Null value. For example, if you change from Single to Integer data type, fractional values will be rounded to the nearest whole number and values greater than 32,767 or less than -32,768 will result in Null fields.

You can't undo changes to a table's design after saving it in table Design view.

Tip   You can use the Currency data type if you plan to perform many calculations on a field that contains data with one to four decimal places. Single and Double data type fields require floating-point calculation. Currency data type fields use a faster fixed-point calculation.


IgnoreNulls Property (Microsoft Access)

You can use the IgnoreNulls property to specify that records with Null values in the indexed fields are not included in the index.

Setting

The IgnoreNulls property uses the following settings.

Setting	Description	Visual Basic
Yes	Records that contain Null values in the indexed fields aren't included in the index.	True (-1)
No	Records that contain Null values in the indexed fields are included in the index.	False (0)
You can set this property in the Indexes window of table Design view or in Visual Basic.

Note   To access the IgnoreNulls property of an index using Visual Basic, use the Data Access Object's IgnoreNulls property.

Remarks

You can define an index for a field to facilitate fast searches for records using that field. If you allow Null entries in the indexed field and expect to have many of them, set the IgnoreNulls property for the index to Yes to reduce the amount of storage space that the index uses.


Indexed Property

You can use the Indexed property to set a single-field index. An index speeds up queries on the indexed fields as well as sorting and grouping operations. For example, if you search for specific employee names in a LastName field, you can create an index for this field.

Setting

The Indexed property uses the following settings.

Setting	Description

No	(Default) No index.

Yes (Duplicates OK)	The index allows duplicates.

Yes (No Duplicates)	The index doesn't allow duplicates.

You can set this property only in the table's property sheet. You can also click Indexes on the View menu, or click the Indexes button on the toolbar. Microsoft Access then displays the Indexes window. If you add a single-field index in the Indexes window, Microsoft Access will set the Indexed property to Yes.

In Visual Basic, use the Data Access Objects CreateIndex method to create an index for a field.

Remarks

Use the Indexed property to find and sort records using a single field in a table. The field can hold either unique or non-unique values. For example, you can create an index on an EmployeeID field in an employees table in which each employee ID is unique or you can create an index on a name field in which some names may be duplicates.

Note   You can't index Memo and OLE Object data type fields.

You can create as many indexes as you need. The indexes are created when you save the table design and are automatically updated when you change or add records. You can add or delete indexes at any time in table Design view.

Tip   You can specify text that is commonly used at the beginning or the end of a field name (such as "ID", "code", or "num") for the AutoIndex On Import/Create option on the Tables/Queries tab, available by clicking Options on the Tools menu. When you import data files that contain this text in their field names, Microsoft Access creates an index for these fields.

If the primary key for a table is a single field, Microsoft Access will automatically set the Indexed property for that field to Yes (No Duplicates).

If you want to create multiple-field indexes, use the Indexes window.


Primary Property (Microsoft Access)

You can use the Primary property to specify whether the index is the primary key for the table. A primary key uniquely identifies each record in a table and prevents you from entering duplicate values in a primary key field.

Setting

The Primary property uses the following settings.

Setting	Description	Visual Basic
Yes	The selected index is the primary key.	True (-1)
No	The selected index isn't the primary key.	False (0)
You can set the Primary property in three ways:

In table Design view, select the field or fields in the order you want for the primary key and then click Primary Key on the Edit menu or click the Primary Key button on the toolbar.

In the Indexes window, select or enter the name of an index in the Index Name column and set the Primary property to Yes in the Index Properties list.

In Visual Basic to access the Primary property of an index in Visual Basic, use the Data Access Objects Primary property.

Remarks

Microsoft Access creates an index on the primary key of the table and uses it to find records and to create joins between tables. The primary key index requires an entry in each primary key field and allows no duplicates. The order of the fields determines the default sort order for the table.

If there is no primary key when you save a table design, Microsoft Access will display a dialog box asking whether you want a primary key to be created. If you choose Yes, an AutoNumber data type field will be added to the table (with its NewValues property set to Increment) and set as the primary key. If you choose No, no primary key will be created.

A table with no primary key can't be used in a relationship and can be slower to sort and search.


Required Property (Microsoft Access)

You can use the Required property to specify whether or not a value is required in a field. If this property is set to Yes, when you enter data in a record you must enter a value in the field or in any control bound to the field, and the value cannot be Null. For example, you might want to be sure that a LastName control has a value for each record. When you want to permit Nulls in a field you must not only set the Required property to No but if there is a Validation Rule it must explicitly state "Null Or (...other validation rules...)".

Note   The Required property doesn't apply to AutoNumber fields.

Setting

The Required property uses the following settings.

Setting	Description	Visual Basic
Yes	The field requires a value.	True (-1)
No	(Default) The field doesn't require a value.	False (0)
You can set this property for all table fields (except AutoNumber data type fields) in the table's property sheet or Visual Basic.

Note   To access a field's Required property in Visual Basic, use the Data Access Object's Required property.

Remarks

The Required property is enforced at the table level by the Microsoft Jet database engine. If you set this property to Yes, the field must receive or already contain a value when it has the focus [image] when a user enters data in a table (or in a form or datasheet based on the table), when a macro or Visual Basic sets the value of the field, or when data is imported into the table.

You can use the Required and AllowZeroLength properties to differentiate between information that doesn't exist (stored as a zero-length string (" ") in the field) and information that may exist but is unknown (stored as a Null value in the field). If you set the AllowZeroLength property to Yes, a zero-length string will be a valid entry in the field regardless of the Required property setting. If you set Required to Yes and AllowZeroLength to No, you must enter a value in the field, and a zero-length string won't be a valid entry.

Note   You need to use an input mask when data is entered in a field to distinguish between the display of a Null value and a zero-length string. For example, the string "None" could be displayed when a zero-length string is entered.

The following table shows the results you can expect when you combine the settings of the Required and AllowZeroLength properties.

Required	AllowZeroLength	User's action	Value stored
No	No	Presses ENTER Presses SPACEBAR Enters a zero-length string	Null Null (not allowed)
No	Yes	Presses ENTER Presses SPACEBAR Enters a zero-length string	Null Null Zero-length string
Yes	No	Presses ENTER Presses SPACEBAR Enters a zero-length string	(not allowed) (not allowed) (not allowed)
Yes	Yes	Presses ENTER Presses SPACEBAR Enters a zero-length string	(not allowed) Zero-length string Zero-length string
If you set the Required property to Yes for a field in a table that already contains data, Microsoft Access gives you the option to check whether the field has a value in all existing records. However, you can require that a value be entered in this field in all new records even if there are existing records with Null values in the field.

Note   To enforce a relationship between related tables that do not allow Null values, set the Required property of the foreign key field in the related table to Yes. The Jet database engine then ensures that you have a related record in the parent table before you can create a record in the child table. If the foreign key field is part of the primary key of the child table, this is unnecessary, because a primary key field can't contain a Null value.


DisplayControl Property

You can use the DisplayControl property in table Design view to specify the default control you want to use for displaying a field.

Setting

The DisplayControl property contains a drop-down list of the available controls for the selected field. For fields with a Text or Number data type, the DisplayControl property can be set to Text Box, List Box, or Combo Box. For fields with a Yes/No data type, the DisplayControl property can be set to Check Box, Text Box, or Combo Box.

You can set this property in the table's property sheet in table Design view by clicking the Lookup tab under Field Properties.

Microsoft Access sets the DisplayControl property automatically when you select Lookup Wizard as the data type for a field in table Design view.

Remarks

When you select a control for the DisplayControl property, any additional properties needed to configure the control are also displayed on the Lookup tab.

Tip   Let Microsoft Access set the DisplayControl property and any related properties for you by using the Lookup Wizard.

Setting the DisplayControl property and any related control type properties will affect the field display in both Datasheet view and Form view. The field is displayed using the control and control property settings set in table Design view. If a field had its DisplayControl property set in table design view and you drag it from the field list in form Design view, Microsoft Access copies the appropriate properties to the control's property sheet.


DatasheetCellsEffect Property

You can use the DatasheetCellsEffect property to specify whether special effects are applied to cells in a datasheet.

Note   The DatasheetCellsEffect property applies only to objects in Datasheet view.

Setting

The DatasheetCellsEffect property uses the following settings.

Setting	Description	Visual Basic	Value
Flat	(Default) No special effects are applied to the cells in the datasheet.	acEffectNormal	0
Raised	Cells in the datasheet appear raised.	acEffectRaised	1
Sunken	Cells in the datasheet appear sunken.	acEffectSunken	2
You can set this property using the Formatting toolbar (in Datasheet view), a macro, or Visual Basic.

You can also set this property by choosing Cells from the Format menu.

You can set the default DatasheetCellsEffect property using the Datasheet tab of the Options dialog on the Tools menu.

Remarks

The DatasheetCellsEffect property applies the selected effect to the entire datasheet.

When the DatasheetCellsEffect property is set to Raised or Sunken, grid lines will be visible on the datasheet regardless of the DatasheetGridLinesBehavior property setting.


DatasheetGridLinesColor Property

You can use the DatasheetGridLinesColor property to specify the color of grid lines in a datasheet.

Note   The DatasheetGridLinesColor property applies only to objects in Datasheet view.

Setting

The DatasheetGridLinesColor property setting is a numeric expression using a Long Integer data type. In Visual Basic, you can also use the RGB or QBColor functions to set this property.

You can set this property using the Formatting toolbar (in Datasheet view), a macro, or Visual Basic.

You can also set this property by choosing Cells from the Format menu.

You can set the default DatasheetGridLinesColor property using the Datasheet tab of the Options dialog on the Tools menu.

Remarks

This property setting affects the grid line color for the entire datasheet. It's not possible to set the grid line color of individual cells in Datasheet view.


DatasheetGridLinesBehavior Property

You can use the DatasheetGridLinesBehavior property to specify which grid lines will appear in Datasheet view.

Note   This DatasheetGridLinesBehavior property applies only to objects in Datasheet view.

Setting

The DatasheetGridLinesBehavior property uses the following settings.

Setting	Description	Visual Basic	Value
Both	(Default) Horizontal and vertical grid lines are displayed.	acGridLinesBoth	0
Horizontal	Only horizontal grid lines are displayed.	acGridLinesHoriz	1
Vertical	Only vertical grid lines are displayed.	acGridLinesVert	2
None	No grid lines are displayed.	acGridLinesNone	3
You can set this property using the Formatting toolbar (in Datasheet view), a macro, or Visual Basic.

You can also set this property by choosing Cells from the Format menu.

You can set the default DatasheetGridLinesBehavior property using the Datasheet tab of the Options dialog on the Tools menu.

Remarks

Changes to the DatasheetGridLinesBehavior property will only be visible if the DatasheetCellsEffect property is set to Flat.


NewValues Property

You can use the NewValues property to specify how AutoNumber fields increment when new records are added to a table.

Note   The NewValues property applies only to AutoNumber fields.

Setting

The NewValues property uses the following settings.

Setting	Description

Increment	(Default) AutoNumber field values increment by 1 for new records.

Random	AutoNumber field values are assigned a random Long Integer for new records.

You can set this property in the table's property sheet in table Design view by clicking the General tab under Field Properties.

Remarks

When you replicate a database, AutoNumber field settings are set to Random to ensure that new records entered in different replicas will have unique values.


FontBold Property

You can use the FontBold property to specify whether a font appears in a bold style in a control or when you use the Print method on a report.

Setting

The FontBold property uses the following settings.

Setting	Description

True (-1)	Text is bold.

False (0)	(Default) Text isn't bold.

You can set the FontBold property only using Visual Basic.

Remarks

To use the FontBold property on a report, first create a Print event procedure that prints the desired text.

The font's appearance on screen and in print may differ, depending on your computer and printer. If you select a font that your system can't display or that isn't installed, Windows substitutes a similar font.


FontBold Property Example

You can use the following event procedure to print the current date in a bold font on a report at the coordinates specified by the CurrentX and CurrentY property settings.

Sub ReportHeader0_Print (Cancel As Integer, PrintCount As Integer)

Me.FontBold = True

Me.Print Date()	  ' Print date in bold.

End Sub


 Specifying Criteria

When working with data you will often need to specify criteria to restrict your data to a specific set.  For example, you specify criteria for your data when you use domain aggregate functions.  You may also specify criteria when you use the Find methods of a Recordset object, set the Filter property of a form, or construct an SQL statement.  The information below explains how to specify criteria for domain aggregate functions, but you can apply the same techniques to other situations in which you specify criteria to restrict a resulting set of data.

All of the domain aggregate functions have an identical syntax:

DFunction(expr, domain[, criteria])

The criteria argument is an optional argument that enables you to restrict the range of data on which the domain function is performed. If you don't specify a value for criteria, the domain function is performed on the entire set of records in the table or query defined by domain.

For example, you can use the DSum function to find the sum total of all freight costs in the Orders table. You could create a calculated control by entering the following expression in the ControlSource property:

= DSum("[Freight]", "Orders")

If you specify a criteria argument, the domain function will be performed on a subset of domain. For example, you could use the DSum function to find the sum total of all freight costs in the Orders table for only those orders being shipped to California.

= DSum("[Freight]", "Orders", "[Ship Region] = 'CA'")

When you supply a criteria argument for a domain function, Microsoft Access first evaluates any expressions included in the argument to form a string expression. Then the string expression is passed to the domain function. The string expression is equivalent to an SQL WHERE clause, without the word WHERE.

You can specify numeric, textual, or date/time criteria. No matter what type of criteria you specify, the criteria argument is always converted to a string before being passed to the domain function. Therefore, you must make certain that after any expressions have been evaluated, all parts of the argument are concatenated into a single string, the whole of which is enclosed in double quotation marks (").

Use caution when constructing criteria to ensure that the string will be properly concatenated.

The following list outlines the different ways in which you can specify criteria for a domain function:

Specifying Numeric Criteria

Specifying Textual Criteria

Specifying Date and Time Criteria

Specifying Numeric Criteria from a Control on a Form

Specifying Textual Criteria from a Control on a Form

Specifying Date and Time Criteria from a Control on a Form

Specifying Multiple Fields in Criteria


Specifying Numeric Criteria

To specify numeric criteria for a criteria argument, you supply a numeric value as part of the string expression.

Suppose that you are performing the DLookup function on an Employees table to find the last name of a particular employee, and you want to use a value from the Employee ID field in the function's criteria argument. You could construct the criteria argument as in the following example, which returns the last name of the employee whose Employee ID is 7.

= DLookup("[Last Name]", "Employees", "[Employee ID] = 7")


Specifying Textual Criteria

To specify textual criteria for a criteria argument, you supply a text string as part of the string expression. This text string must be enclosed in single quotation marks (').

Note   The single quotation marks permit the criteria argument to contain a string within a string.

Suppose that you are performing the DLookup function on an Employees table to find the last name of a particular employee, and you want to use the employee's first name as the criteria argument for the function. You could construct the criteria argument as in the following example, which returns the last name of the employee whose first name is Andrew. Note that the string literal Andrew is enclosed in single quotation marks.

= DLookup("[Last Name]", "Employees", "[First Name] = 'Andrew'")


Specifying Date and Time Criteria

To specify date or time criteria for a criteria argument, you supply a date or time value as part of the string expression. This value must be enclosed in number signs (#).

Note   The number signs permit the criteria argument to contain a date or time within a string.

Suppose that you are performing the DLookup function on an Employees table to find the name of an employee whose birthday is on a given date. You could construct the criteria argument as in the following example, which returns the last name of the employee whose birth date is 11-15-67. Note the placement of the number signs.

= DLookup("[Last Name]", "Employees", "[Birth Date] = #11-15-67#")


Specifying Numeric Criteria from a Control on a Form

If you want to change the criteria argument of a domain aggregate function based on a user's decision, you can specify that the criteria comes from a control on a form. For example, you could specify that the criteria argument comes from a text box containing the Employee ID number.

To specify numeric criteria that comes from a control on a form, you include in the criteria argument an expression that references that control. This expression should be separate from the string expression, so that it will be evaluated first, and then concatenated with the rest of the string expression. The entire concatenated string expression, which must be enclosed in double quotation marks ("), is then passed to the function.

Suppose that you are performing the DLookup function on an Employees table to find the last name of an employee based on the Employee ID number. In the following example, the criteria is determined by the current value of the Employee ID control on the Orders form. The expression referencing the control is evaluated each time the function is called, so that if the value of the control changes, the criteria argument will reflect that change.

= DLookup("[Last Name]", "Employees", "[Employee ID] = " & Forms!Orders![Employee ID])

If the current value of the Employee ID field is 7, the criteria argument that is passed to the DLookup function is:

"[Employee ID] = 7"

Tip   To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Debug window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.

You can also include a variable representing a numeric value in the criteria argument. The variable should be separate from the string expression, so that it will be evaluated first. The result is then concatenated with the rest of the string expression.

The following example shows how to construct a criteria argument that includes a variable.

Dim intNum as Integer, Result as Variant

intNum = 7

Result = DLookup("[Last Name]", "Employees", "[Employee ID] = " & intNum)


Specifying Textual Criteria from a Control on a Form

If you want to change the criteria argument of a domain aggregate function based on a user's decision, you can specify that the criteria comes from a control on a form. For example, you could specify that the criteria argument comes from a list box containing the last names of all employees in an Employees table.

To specify textual criteria that comes from a control on a form, you include in the criteria argument an expression that references the control on the form. This expression should be separate from the string expression, so that it will be evaluated first, and then concatenated with the rest of the string expression. The entire concatenated string expression, which must be enclosed in double quotation marks ("), is then passed to the function.

In addition to enclosing the entire string expression in double quotation marks, you must also ensure that the textual criteria within the string expression is enclosed in single quotation marks ('). The single quotation marks must be included in the strings flanking the expression that references the control on the form.

Note   The single quotation marks permit the criteria argument to contain a string within a string.

The following example performs a lookup on an Employees table and returns the region in which an employee lives, based on the employee's last name. The criteria is determined by the current value of a list box control called Last Name on the Employees form. Note the placement of the single quotation marks.

= DLookup("[Region]", "Employees", "[Last Name] = '" & Forms!Employees![Last Name] & "'")

If the current value of the control is King, the criteria argument that is passed to the DLookup function is:

"[Last Name] = 'King'"

Tip   To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Debug window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.

You can also include a variable representing a textual string in the criteria argument. The variable should be separate from the string expression, so that it will be evaluated first. The result is then concatenated with the rest of the string expression. The textual string must be enclosed in single quotation marks.

The following example shows how to construct a criteria argument that includes a variable representing a textual string.

Dim strLastName as String, Result as Variant

strLastName = "King"

Result = DLookup("[Last Name]", "Employees", "[Employee ID] = '" & strLastName & "'")


Specifying Date and Time Criteria from a Control on a Form

If you want to change the criteria argument of a domain aggregate function based on a user's decision, you can specify that the criteria comes from a control on a form. For example, you could specify that the criteria argument comes from a list box containing order dates from an Orders table.

To specify date or time criteria that comes from a control on a form, you include in the criteria argument an expression that references the control on the form. This expression should be separate from the string expression, so that it will be evaluated first, and then concatenated with the rest of the string expression. The entire concatenated string expression, which must be enclosed in double quotation marks ("), is then passed to the function.

In addition to enclosing the entire string expression in double quotation marks, you must also ensure that the date or time criteria within the string expression is enclosed in number signs (#). The number signs must be included in the strings flanking the expression that references the control on the form.

Note   The number signs permit the criteria argument to contain a date or time within a string.

The following example performs a lookup on an Orders table and returns the Ship Name, based on the order date. The criteria is determined by the current value of a list box control called Order Date on the Orders form. Note the placement of the number signs.

= DLookup("[Ship Name]", "Orders", "[Order Date] = #" & Forms!Orders![Order Date] & "#")

If the current value of the control is 3-30-94, the criteria argument that is passed to the DLookup function is:

"[Last Name] = #3-30-94#"

Tip   To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Debug window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.

You can also include a variable representing a date or time in the criteria argument. The variable should be separate from the string expression, so that it will be evaluated first. The result is then concatenated with the rest of the string expression. The date or time criteria must be enclosed in number signs.

The following example shows how to construct a criteria argument that includes a variable representing a date or time.

Dim datOrderDate As string, Result As Variant

datOrderDate = 3-3-94

Result = DLookup("[Ship Name]", "Orders", "[Ship Date] = #" & datOrderDate & "#")


Specifying Multiple Fields in Criteria

You can specify multiple fields in the criteria argument of a domain aggregate function.

To specify multiple fields in the criteria, you must ensure that multiple string expressions are concatenated correctly to form a valid SQL WHERE clause. In an SQL WHERE clause with multiple fields, fields may be joined with one of three keywords: AND, OR, or NOT. Your expression must evaluate to a string that includes one of these keywords.

For example, suppose that you wish to find the last name of an employee based on the region in which the employee lives and the employee's hire date. The region comes from a control on the Employees form called Region, and the hire date comes from a control called Hire Date. You could construct the argument as follows.

= DLookup("[Last Name]", "Products", "[Region] = '" & Forms!Employees![Region] _

& "' AND [Hire Date] = #" & Forms!Employees![Hire Date] & "#")

If the current value of the Region control is WA, and the current value of the Hire Date control is 3-1-93, then the criteria argument that is passed to the DLookup function is:

"[Region] = 'WA' AND [Hire Date] = #3-1-93#"

Tip   To troubleshoot an expression in the criteria argument, break the expression into smaller components and test each individually in the Debug window. When all of the components are working correctly, put them back together one at a time until the complete expression works correctly.


Using Quotation Marks in Strings

In situations where you must construct strings, you may need to embed a string within another string, or a string variable within a string. Some of the situations that you might need to nest one string within another include:

When specifying criteria for domain aggregate functions.

When specifying criteria for the Find methods.

When building SQL strings.

In all of these instances, Microsoft Access must pass a string to the Microsoft Jet database engine. When you specify a criteria argument for a domain aggregate function, for example, Microsoft Access must evaluate any variables, concatenate them into a string, and then pass the entire criteria string to the Jet database engine.

If you embed a numeric variable, Microsoft Access evaluates the variable and simply concatenates the value into the string. If the variable is a text string, however, the resulting criteria string will contain a string within a string. A string within a string must be identified by string delimiters. Otherwise, the Jet database engine won't be able to determine which part of the string is the value you want it to use.

The string delimiters aren't actually part of the variable itself, but they must be included in the criteria string. You can use either single (') or double (") quotation marks. There are three different ways to construct the criteria string. Each method results in a criteria string that looks like one of the two following examples.

"[Last Name] = 'Smith'"

-Or-

"[Last Name] = "Smith""

Include Single Quotation Marks

You should include single quotation marks in the criteria string in such a way that when the value of the variable is concatenated into the string, it will be enclosed within the single quotation marks. For instance, suppose your criteria argument must contain a string variable called strName. You could construct the criteria argument as in the following example.

"[Last Name] = '" & strName & "'"

When the variable strName is evaluated and concatenated into the criteria string, the criteria string becomes:

"[Last Name] = 'Smith'"

Note   This syntax does not permit the use of apostrophes within the value of the variable itself. If the value of the string variable includes an apostrophe, Microsoft Access will generate a run-time error. If your variable may represent values containing apostrophes, consider using one of the other syntax forms discussed below.

Include Double Quotation Marks

You should include double quotation marks within the criteria string in such a way so that when the value of the variable is evaluated, it will be enclosed within the quotation marks. Within a string, you must use two sets of double quotation marks to represent a single set of double quotation marks. You could construct the criteria as in the following example.

"[Last Name] = """ & strName & """"

When the variable strName is evaluated and concatenated into the criteria string, each set of two double quotation marks is replaced by one double quotation mark. The criteria string becomes:

"[Last Name] = "Smith""

This syntax may appear more complicated than the apostrophe syntax, but it enables you to embed a string that contains an apostrophe within the criteria string. It also enables you to nest one or more strings within the embedded string.

Include a Variable Representing Quotation Marks

You can create a string variable that represents double quotation marks, and concatenate this variable into the criteria string along with the value of the variable. The ANSI representation for double quotation marks is Chr$(34); you could assign this value to a string variable called strQuote. You could then construct the criteria argument as in the following example.

"[Last Name] = & strQuote & strName & strQuote "

When the variables are evaluated and concatenated into the criteria string, the criteria string becomes:

"[Last Name] = "Smith""


Using Microsoft Access as a DDE Server
‚Using Microsoft Access as a DDE Server

Microsoft Access supports dynamic data exchange (DDE) as either a destination (client) application or a source (server) application. For example, an application such as Microsoft Word, acting as a client, can request data through DDE from a Microsoft Access database which is acting as a server.

Tip   If you need to manipulate Microsoft Access objects from another application, you may want to consider using OLE Automation.

A DDE conversation between a client and server is established on a particular topic. A topic can be either a data file in the format supported by the server application, or it can be the system topic, which supplies information about the server application itself. Once a conversation has begun on a particular topic, only a data item associated with that topic can be transferred.

For example, suppose you are running Microsoft Word for Windows and want to insert data from a particular Microsoft Access database into a document. You begin a DDE conversation with Microsoft Access by opening a DDE channel with the DDEInitiate function and specifying the database filename as the topic. You can then transfer data from that database to Microsoft Word through that channel.

As a DDE server, Microsoft Access supports the following topics:

The System topic

The name of a database (database topic)

The name of a table (tablename topic)

The name of a query (queryname topic)

A Microsoft Access SQL string (sqlstring topic)

Once you have established a DDE conversation, you can use the DDEExecute statement to send a command from the client to the server application. When used as a DDE server, Microsoft Access recognizes any of the following as a valid command:

The name of a macro in the current database.

Any action that you can carry out in Visual Basic using one of the methods of the DoCmd object.

The OpenDatabase and CloseDatabase actions, which are used only for DDE operations. (For an example of how to use these actions, see the example later in this topic.)

Note   When you specify a macro action as a DDEExecute statement, the action and any arguments follow the DoCmd object syntax and must be enclosed in brackets ([ ]). However, applications that support DDE don't recognize intrinsic constants in DDE operations. Also, string arguments must be enclosed in quotation marks (" ") if the string contains a comma. Otherwise, quotation marks aren't required.

The client application can use the DDERequest function to request text data from the server application over an open DDE channel. Or the client can use the DDEPoke statement to send data to the server application. Once the data transfer is complete, the client can use the DDETerminate statement to close the DDE channel, or the DDETerminateAll statement to close all open channels.

Note   When your client application has finished receiving data over a DDE channel, it should close that channel to conserve memory resources.

The following example demonstrates how to create a Word for Windows WordBasic macro that uses Microsoft Access as a DDE server. (For this example to work, Microsoft Access must either be running or be listed in the path command in your Autoexec.bat file.)

Sub MAIN
' Using System topic, open Northwind.mdb database.
' Database must be open before using other DDE topics.
Chan1 = DDEInitiate("MSAccess", "System")
DDEExecute Chan1, "[OpenDatabase C:\Msoffice\Access\Samples\Northwind.mdb]"

' Get all data from Sales By Year query.
Chan2 = DDEInitiate("MSAccess", "Northwind.mdb;QUERY Sales By Year")
QueryData$ = DDERequest$(Chan2, "All")
DDETerminate Chan2

' Close database.
DDEExecute Chan1, "[CloseDatabase]"
DDETerminate Chan1

' Insert data into text file.
Open "C:\DATA.TXT" For Append As #1
Print #1, QueryData$
Close #1
End Sub

For information on using Microsoft Access as a DDE client, see Chapter 11, "Communicating with Other Applications," in Building Applications with Microsoft Access for Windows 95.

The following sections provide information about the valid DDE topics supported by Microsoft Access.

The System Topic

The System topic is a standard topic for all Microsoft Windows-based applications. It supplies information about the other topics supported by the application. To access this information, your code must first call the DDEInitiate function with "System" as topic, and then execute the DDERequest statement with one of the following supplied for the item argument.

Item	Returns

SysItems	A list of items supported by the System topic in Microsoft Access.

Formats	A list of the formats Microsoft Access can copy onto the Clipboard.

Status	"Busy" or "Ready."

Topics	A list of all open databases.

The following example demonstrates using the DDEInitiate and DDERequest functions with the System topic.

' In WordBasic macro, initiate DDE conversation with Microsoft Access.
Chan1 = DDEInitiate("MSAccess", "System")
' Request list of topics supported by System topic.
Res$ = DDERequest$(Chan1, "SysItems")
' Run OpenDatabase action to open Northwind.mdb.
DDEExecute Chan1, "[OpenDatabase C:\Access\Samples\Northwind.mdb]"

The database Topic

The database topic is the filename of an existing database. You can type either just the base name (Northwind), or its path and .mdb extension (C:\Access\Samples\Northwind.mdb). After you start a DDE conversation with the database, you can request a list of the objects in that database.

Note   You can't use DDE to query the Microsoft Access workgroup information file.

The database topic supports the following items.

Item	Returns

TableList	A list of tables.

QueryList	A list of queries.

FormList	A list of forms.

ReportList	A list of reports.

MacroList	A list of macros.

ModuleList	A list of modules.

The following example shows how you can open the Employees form in the Northwind sample database from a WordBasic macro.

' In WordBasic macro, initiate DDE conversation with Northwind.mdb.
' Make sure database is open.
Chan2 = DDEInitiate("MSAccess", "Northwind")
' Request list of forms in Northwind.mdb.
Res$ = DDERequest$(Chan2, "FormList")
' Run OpenForm action and arguments to open Employees form.
DDEExecute Chan2, "[OpenForm Employees,0,,,1,0]"

The TABLE tablename, QUERY queryname, and SQL sqlstring Topics

These topics use the following syntax:

databasename; TABLE tablename

databasename; QUERY queryname

databasename; SQL [sqlstring]

Part	Description

databasename	The name of the database that the table or query is in or that the SQL statement Applies To, followed by a semicolon (;). The database name can be just the base name (Northwind) or its full path and .mdb extension (C:\Access\Samples\Northwind.mdb).

tablename	The name of an existing table.

queryname	The name of an existing query.

sqlstring	A valid SQL statement up to 256 characters long, ending with a semicolon. To exchange more than 256 characters, omit this argument and instead use successive DDEPoke statements to build an SQL statement.

For example, the following WordBasic code uses DDEPoke to build an SQL statement and then request the results of the query.

Chan1 = DDEInitiate("MSAccess", "Northwind;SQL")
DDEPoke Chan1, "SQLText", "SELECT *"
DDEPoke Chan1, "SQLText", " FROM Orders"
DDEPoke Chan1, "SQLText", " WHERE [Freight] > 100;"
Res$ = DDERequest$(Chan1, "NextRow")
DDETerminate Chan1

The following table lists the valid items for the TABLE tablename, QUERY queryname, and SQL sqlstring topics.

Item	Returns

All	All the data in the table, including field names.

Data	All rows of data, without field names.

FieldNames	A single-row list of field names.

FieldNames;T	A two-row list of field names (first row) and their data types (second row).

These are the values returned and the data types they represent:

0	Invalid

1	True/False (non-Null)

2	Unsigned byte ( )

3	2-byte signed integer (Integer)

4	4-byte signed integer (Long)

5	8-byte signed integer (Currency)

6	4-byte single-precision floating-point (Single)

7	8-byte double-precision floating-point (Double)

8	Date/Time (integral date, fractional time)

9	Binary data, 256 bytes maximum

10	ANSI text, not case-sensitive, 256 bytes maximum (Text)

11	Long binary (OLE Object)

12	Long text (Memo)

NextRow	The data in the next row in the table or query. When you open a channel, NextRow returns the data in the first row. If the current row is the last record and you run NextRow, the request fails.

PrevRow	The data in the previous row in the table or query. If PrevRow is the first request on a new channel, the data in the last row of the table or query is returned. If the first record is the current row, the request for PrevRow fails.

FirstRow	The data in the first row of the table or query.

LastRow	The data in the last row of the table or query.

FieldCount	The number of fields in the table or query.

SQLText	A SQL statement representing the table or query. For tables, this item returns a SQL statement in the form "SELECT * FROM table;".

SQLText;n	A SQL statement, in n-character chunks, representing the table or query, where n is an integer up to 256. For example, suppose a query is represented by the following SQL statement:

"SELECT * FROM Orders;"

The item "SQLText;7" returns the following tab-delimited chunks:

"SELECT "
"* FROM "
"Orders;"

The following example shows how you can use DDE in a WordBasic macro to request data from a table in the Northwind sample database and insert that data into a text file.

Sub MAIN
' In WordBasic macro, get data from Categories table,
' Catalog query, and Orders table in Northwind.mdb.
' Make sure database is open.
Chan1 = DDEInitiate("MSAccess", "Northwind;TABLE Categories")
Chan2 = DDEInitiate("MSAccess", "Northwind;QUERY Catalog")
Chan3 = DDEInitiate("MSAccess", "Northwind;SQL SELECT * FROM Orders")

Res1$ = DDERequest(Chan1, "All")
Res2$ = DDERequest(Chan2, "FieldNames;T")
Res3$ = DDERequest(Chan3, "FieldNames;T")

DDETerminate Chan1
DDETerminate Chan2
DDETerminate Chan3

' Insert data into text file.
Open "DATA.TXT" For Append As #1
Print #1, Res1$
Print #1, Res2$
Print #1, Res3$
Close #1
End Sub


DDE Functions and Statements

DDE Function

DDEExecute Statement

DDEInitiate Function

DDEPoke Statement

DDERequest Function

DDESend Function

DDETerminate Statement

DDETerminateAll Statement


DDEExecute Statement

You can use the DDEExecute statement to send a command from a client application to a server application over an open dynamic data exchange (DDE) channel.

For example, suppose you have opened a DDE channel in Microsoft Access to transfer text data from a Microsoft Excel spreadsheet into a Microsoft Access database. Use the DDEExecute statement to send the New command to Microsoft Excel to specify that you wish to open a new spreadsheet. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEExecute channum, command

The DDEExecute statement syntax has these arguments.

Argument	Description

channum	The channel number returned by the DDEInitiate function.

command	A string expression specifying a command recognized by the server application. Check the server application's documentation for a list of these commands.

Remarks

The value of command depends on the application and topic specified when the channel channum is opened. An error occurs if channum isn't an integer corresponding to an open channel or if the other application can't carry out the specified command.

From Visual Basic, you can use the DDEExecute statement only to send commands to another application. For information on sending commands to Microsoft Access from another application, see Using Microsoft Access as a DDE Server.

Tip   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.


DDEExecute Statement Example

This example establishes a DDE link with Microsoft Excel, places some values into cells in the first row of a new worksheet, and charts the values. First, the DDEInitiate function opens a channel to begin the DDE conversation. Then, the DDEExecute statement sends Microsoft Excel the command to open a new worksheet, and the DDERequest function asks Microsoft Excel for the name of the newly created worksheet. A new channel is opened, and the DDEPoke statement sends to Microsoft Excel the data to be charted. Finally, the DDETerminate statement terminates the DDE link with Microsoft Excel, and the DDETerminateAll statement terminates all active DDE links.

On Error Resume Next	' Set up error handler.
Dim Chan, SheetName, I, TopicList	' Declare variables.
Chan = DDEInitiate("Excel", "System")	' Establish spreadsheet link.
If Err Then	' If error occurs, spreadsheet
Err = 0	' isn't running. Reset error
I = Shell("Excel", 1)	' and start spreadsheet.
If Err Then Exit Sub	' If another error, exit.
Chan = DDEInitiate("Excel", "System")	' Establish spreadsheet link.
End If
DDEExecute Chan, "[New(1)]"	' Create new worksheet.
TopicList = DDERequest(Chan, "Selection")' Get topic list, worksheet
' name.
SheetName = Left(TopicList, InStr(1, TopicList, "!") - 1)
DDETerminate Chan	' Terminate DDE link.
Chan = DDEInitiate("Excel", SheetName) 	' Establish link with new
' worksheet.
For I = 1 To 10	' Put some values into
DDEPoke Chan, "R1C" & I, I	' first row.
Next I
DDEExecute Chan, "[Select(""R1C1:R1C10"")][New(2,2)]"	' Make chart.
DDETerminateAll	' Terminate all links.


DDEInitiate Function

You can use the DDEInitiate function to begin a dynamic data exchange (DDE) conversation with another application. The DDEInitiate function opens a DDE channel for transfer of data between a DDE server and client application.

For example, if you wish to transfer data from a Microsoft Excel spreadsheet to a Microsoft Access database, you can use the DDEInitiate function to open a channel between the two applications. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEInitiate(application, topic)

The DDEInitiate function has these arguments.

Arguments	Description

application	A string expression identifying an application that can participate in a DDE conversation. Usually, application is the name of an .exe file (without the .exe extension) for a Microsoft Windows-based application, such as Microsoft Excel.

topic	A string expression that is the name of a topic recognized by application. Check the application's documentation for a list of topics.

Remarks

If successful, the DDEInitiate function begins a DDE conversation with the specified application and topic and returns a Variant containing an integer value. This integer represents a unique channel number identifying a channel over which data transfer can take place. This channel number is subsequently used with other DDE functions and statements.

If the application is not already running or if it is running but doesn't recognize topic or doesn't support DDE, the DDEInitiate function returns a run-time error.

The value of topic depends on application. For applications that use documents or data files, valid topic names often include the names of those files.

Note   The maximum number of channels that can be open simultaneously is determined by Windows and your system's memory and resources. If you aren't using a channel, you should conserve resources by terminating it using a DDETerminate or DDETerminateAll statement.

Tip   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.


DDEPoke Statement

You can use the DDEPoke statement to supply text data from a client application to a server application over an open dynamic data exchange (DDE) channel.

For example, if you have an open DDE channel between Microsoft Access, and Microsoft Excel, you can use the DDEPoke statement to transfer text from a Microsoft Access database to a Microsoft Excel spreadsheet. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDEPoke channum, item, data

The DDEPoke statement syntax has these arguments.

Argument	Description

channum	A channel number, an integer value returned by the DDEInitiate function.

item	A string expression that is the name of a data item recognized by application. Check the application's documentation for a list of possible items.

data	A string containing the data to be supplied to the other application.

Remarks

The value of item depends on the application and topic specified when the channel channum is opened. For example, item may be a range of cells in a Microsoft Excel spreadsheet.

The string comprising data must be an alphanumeric text string. No other formats are supported. For instance, data could be a number to fill a cell in a specified range in an Excel worksheet.

If channum isn't an integer corresponding to an open channel or if the other application doesn't recognize or accept the specified data, an error occurs.

Tip   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.


DDERequest Function

You can use the DDERequest function over an open dynamic data exchange (DDE) channel to request an item of information from a DDE server application.

For example, if you have an open DDE channel between Microsoft Access and Microsoft Excel, you can use the DDERequest function to transfer text from a Microsoft Excel spreadsheet to a Microsoft Access database. In this example, Microsoft Access acts as the client application, and Microsoft Excel acts as the server application.

Syntax

DDERequest(channum, item)

The DDERequest function syntax has these arguments.

Argument	Description

channum	A channel number, an integer value returned by the DDEInitiate function.

item	A string expression that is the name of a data item recognized by application. Check the application's documentation for a list of possible items.

Remarks

The channum argument specifies the channel number of the desired DDE conversation, and the item argument identifies which data should be retrieved from the server application. The value of item depends on the application and topic specified when the channel channum is opened. For example, item may be a range of cells in a Microsoft Excel spreadsheet.

The DDERequest function returns a Variant containing the requested information as a string if the request was successful.

The data is requested in alphanumeric text format. Graphics or text in any other format cannot be transferred.

If channum isn't an integer corresponding to an open channel, or if the data requested cannot be transferred, an error occurs.

Tip   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.


DDETerminate Statement

You can use the DDETerminate statement to close a specified dynamic data exchange (DDE) channel.

For example, if you have opened a DDE channel to transfer data between Microsoft Excel and Microsoft Access, you can use the DDETerminate statement to close that channel once the transfer is complete.

Syntax

DDETerminate channum

Remarks

The argument channum specifies the channel number to close. It refers to a channel opened by the DDEInitiate function. An error occurs if channum isn't an integer corresponding to an open channel.

Once a channel is closed, any subsequent DDE functions or statements performed on that channel cause an error.

The DDETerminate statement has no effect on active DDE link expressions in fields on forms or reports.

Tip   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.


DDETerminateAll Statement

You can use the DDETerminateAll statement to close all open dynamic data exchange (DDE) channels.

For example, suppose you have opened two DDE channels between Microsoft Excel and Microsoft Access, one to retrieve system information about Microsoft Excel and one to transfer data. You can use the DDETerminateAll statement to close both channels simultaneously.

Syntax

DDETerminateAll

Remarks

Using the DDETerminateAll statement is equivalent to executing a DDETerminate statement for each open channel number. Like the DDETerminate statement, the DDETerminateAll statement has no effect on active DDE link expressions in fields on forms or reports.

If there are no DDE channels open, the DDETerminateAll statement runs without causing an error.

Tip   If you interrupt a procedure that performs DDE, you may inadvertently leave channels open. To avoid exhausting system resources, use the DDETerminateAll statement in your code or from the Immediate tab of the Debug window while debugging code that performs DDE.

Tip   If you need to manipulate another application's objects from Microsoft Access, you may want to consider using OLE Automation.


 BeforeUpdate, AfterUpdate Events

These events occur:

BeforeUpdate [image] before changed data in a control or record is updated.

AfterUpdate [image] after changed data in a control or record is updated.

Notes

Changing data in a control using a macro or Visual Basic doesn't trigger these events for the control. However, if you then move to another record or save the record, the form's BeforeUpdate and AfterUpdate events do occur.

The BeforeUpdate and AfterUpdate events apply only to controls on a form, not controls on a report.

These events don't apply to option buttons, check boxes, or toggle buttons in an option group. They apply only to the option group itself.

Remarks

The BeforeUpdate and AfterUpdate events are triggered when a control or record is updated. Within a record, changed data in each control is updated when the control loses the focus or when the user presses ENTER or TAB. When the focus leaves the record or if the user chooses the Save Record command from the File menu, the entire record is updated, and the data is saved in the database.

When you enter new or changed data in a control on a form and then move to another record or save the record by choosing Save Record from the File menu, the BeforeUpdate and AfterUpdate events for the form occur immediately after the BeforeUpdate and AfterUpdate events for the control. If you moved to a different record, the Exit and LostFocus events for the control then occur, followed by the Current event for the record you moved to, and the Enter and GotFocus events for the first control in this record. To run the BeforeUpdate and AfterUpdate macros or event procedures without running the Exit and LostFocus macros or event procedures, save the record using the Save Record command on the File menu.

BeforeUpdate and AfterUpdate macros and event procedures run only if you change the data in a control. These events don't occur when a value changes in a calculated control. BeforeUpdate and AfterUpdate macros and event procedures for a form run only if you change the data in a record (the data in one or more controls in the record).

For forms, you can use the BeforeUpdate event to cancel updating of a record before moving to another record.

For bound controls, the OldValue property isn't set to the updated value until after the AfterUpdate event occurs. Even if the user enters a new value in the control, the OldValue property setting isn't changed until the data is saved. If you cancel an update, the value of the OldValue property replaces the existing value in the control.

You often use the BeforeUpdate event to validate data, especially when you perform complex validations, such as those that:

Involve conditions for more than one value on a form.

Display different error messages for different data entered.

Can be overridden by the user.

Contain references to controls on other forms or contain user-defined functions.

Note  To perform simple validations or more complex validations, such as requiring a value in a field or validating more than one control on a form, you can use the ValidationRule property for controls and the ValidationRule and Required properties for fields and records in tables.


BeforeUpdate, AfterUpdate Events - Macros
BeforeUpdate, AfterUpdate Events — Macros

To run a macro when the BeforeUpdate or AfterUpdate event occurs, set the BeforeUpdate or AfterUpdate property to the name of the macro. Microsoft Access runs the macro specified by the BeforeUpdate or AfterUpdate property for a control or form before or after the data in the control or in the current record on the form is updated. If the data in the control or record isn't updated, the macro doesn't run.

Remarks

You can use BeforeUpdate macros if you want to store all the validations for a form in one macro group or if you use a validation expression on several forms.

For example, suppose you have a form on which the user enters the name of a country in a Country control and its corresponding postal code in a Postal Code control. You use conditional expressions in the macro to make sure that the data entered in the Country control corresponds to the data entered in the Postal Code control and to display a message if invalid data is entered in the Postal Code control.

You can use an AfterUpdate macro to display a different page in the form or move the focus to a particular control or record. For example, when the user enters a value in a Category control on a form, you can use the GoToPage action in an AfterUpdate macro to move the focus to the page of the form that contains the controls for that category.

You can use the CancelEvent action in a BeforeUpdate macro to cancel the update. If the BeforeUpdate macro is attached to a control, the CancelEvent action returns the focus to the control, and the data the user entered remains in the control.

If a BeforeUpdate macro is attached to a form (in which it runs each time a record is changed), the CancelEvent action returns the focus to the record.

You can't use the CancelEvent action in an AfterUpdate macro.


BeforeUpdate, AfterUpdate Events - Event Procedures
BeforeUpdate, AfterUpdate Events — Event Procedures

To create an event procedure that is run when the BeforeUpdate or AfterUpdate event occurs, set the BeforeUpdate or AfterUpdate property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_BeforeUpdate (Cancel As Integer)

Private Sub controlname_BeforeUpdate (Cancel As Integer)

Private Sub Form_AfterUpdate ( )

Private Sub controlname_AfterUpdate ( )

The BeforeUpdate event procedure uses the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the BeforeUpdate event procedure.
Cancel	The setting determines if the BeforeUpdate event occurs. Setting Cancel to True (-1) cancels the BeforeUpdate event
The AfterUpdate event procedure uses the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the AfterUpdate event procedure.
Remarks

You can't cancel the AfterUpdate event.

You can use an AfterUpdate event procedure to display a different page in the form or move the focus to a particular control or record. For example, when the user enters a value in a Category control on a form, you can use the GoToPage method in the AfterUpdate event procedure for the form to move the focus to the page of the form that contains the controls for that category.


BeforeUpdate, AfterUpdate Events - Event Procedures Example
BeforeUpdate, AfterUpdate Events — Event Procedures Example

This example shows how you can use a BeforeUpdate event procedure to check whether a product name has already been entered. 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 in the database.

To try the following example, add the following code to the Declarations section of 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] ='" & Forms!Products!ProductName & "'"))) Then

MsgBox "Product has already been entered in the database."

Cancel = True

Me!ProductName.Undo

End If

End Sub


Click Event

The Click event occurs when the user presses and then releases a mouse button over an object.

Notes

The Click event applies only to forms, form sections, and controls on a form.

This event doesn't apply to check boxes, option buttons, or toggle buttons in an option group. It applies only to the option group itself.

This event doesn't apply to a label attached to another control, such as the label for a text box. It applies only to "freestanding" labels. Clicking an attached label has the same effect as clicking the associated control. The normal events for the control occur, not any events for the attached label.

Remarks

On a form, this event occurs when the user clicks a blank area of the form or a disabled control on the form.

For a control, this event occurs when the user:

Clicks a control with the left mouse button. Clicking a control with the right or middle mouse button does not trigger this event.

Selects an item in a combo box or list box, either by pressing the arrow keys and then pressing the ENTER key or by clicking the mouse button.

Presses the SPACEBAR when a command button, check box, option button, or toggle button has the focus.

Presses the ENTER key on a form that has a command button whose Default property is set to Yes.

Presses the ESC key on a form that has a command button whose Cancel property is set to Yes.

Presses a control's access key. For example, if a command button's Caption property is set to &Go, pressing ALT+G triggers the event.

Typically, you attach a Click event procedure or macro to a command button to carry out commands and commandlike actions. For the other applicable controls, use this event to trigger actions in response to one of the occurrences discussed earlier in this topic.

The Click event for an option group occurs after you change the value of one of the controls in the option group by clicking the control. For example, if you click a toggle button, option button, or check box in an option group, the Click event for the option group occurs after the BeforeUpdate and AfterUpdate events for the option group.

The Click event for a command button occurs when you choose the command button. In addition, if the command button doesn't already have the focus when you choose it, the Enter and GotFocus events for the command button occur before the Click event.

When a Click event occurs for a list box, the following related events also occur, in this order:

 	MouseDown ⇒ MouseUp ⇒ Click.

Other controls have a similar order of events.

Double-clicking a control causes both DblClick and Click events to occur. For command buttons, double-clicking triggers the following events, in this order:

Click ⇒ DblClick ⇒ Click

You can use a CancelEvent action in a DblClick macro to cancel the second Click event. For more information, see the DblClick event topic.

Tip   To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.


Click Event - Macros
Click Event — Macros

To run a macro when the Click event occurs, set the OnClick property to the name of the macro.

Remarks

You often use Click macros to carry out the actions for each command button on a form. For example, by clicking one command button on a form, users can print a report showing the form's records. By clicking another, they can open a related form.

For a command button only, Microsoft Access runs the macro specified by the OnClick property when the user chooses the command button by pressing the Enter key or an access key. The macro runs once. If you want the macro to run repeatedly while the command button is pressed, set its AutoRepeat property to Yes. For other types of controls, you must click the control using the mouse button to trigger the Click event.

You can't use the CancelEvent action in a Click macro.


Click Event - Event Procedures
Click Event — Event Procedures

To create an event procedure that is run when the Click event occurs, set the OnClick property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Click ( )

Private Sub controlname_Click ( )

The Click event procedure uses the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the Click event procedure.
Remarks

When the user double-clicks a list box, the following events occur, in this order:

MouseDown ⇒ MouseUp ⇒ Click ⇒ DblClick

Other controls have a similar order of events. When you're creating event procedures for these related events, be sure that their event procedure code doesn't conflict. (For example, the DblClick event procedure shouldn't contain code that cancels actions carried out in the Click event procedure.)

For a command button only, Microsoft Access runs the event procedure when the user chooses the command button by pressing the ENTER key or an access key. The event procedure is run once. If you want the event procedure to be run repeatedly while the command button is pressed, set its AutoRepeat property to Yes. For other types of controls, you must click the control using the mouse button to trigger the Click event.

You can't cancel the Click event.


Click Event - Event Procedures Example
Click Event — Event Procedures Example

In this example, the Click event procedure is attached to the ReadOnly check box. The event procedure sets the Enabled and Locked properties of another control on the form, the Amount text box. When the check box is clicked, the event procedure checks whether the check box is being selected or cleared and then sets the text box's properties to enable or disable editing accordingly.

To try the following example, add the code to the Declarations section of a form named Sales that contains a check box called ReadOnly and a text box named Amount.

Private Sub ReadOnly_Click ()
Dim ctl As Control

Set ctl = Forms!Sales!Amount

If Forms!Sales!ReadOnly = True Then	' If checked.
ctl.Enabled = False	' Disable editing.
ctl.Locked = True
Else	' If cleared.
ctl.Enabled = True	' Enable editing.
ctl.Locked = False
End If
End Sub


DblClick Event

The DblClick event occurs when the user presses and releases the left mouse button twice over an object.

On a form, the DblClick event occurs when the user double-clicks a disabled control or a blank area of the form. For a control, it occurs when the user double-clicks a control or its label in Form view. The DblClick event occurs when the user double-clicks the form or control but before the result of the double-click action occurs (for example, before Microsoft Access selects the word that the insertion point is on in a text box).

Notes

The DblClick event applies only to forms, form sections, and controls on a form.

This event doesn't apply to check boxes, option buttons, or toggle buttons in an option group. It applies only to the option group itself.

This event doesn't apply to a label attached to another control, such as the label for a text box. It applies only to "freestanding" labels. Double-clicking an attached label has the same effect as double-clicking the associated control. The normal events for the control occur, not any events for the attached label.

Remarks

For controls, the result of double-clicking depends on the control. For example, double-clicking a word in a text box selects the entire word. Double-clicking a control containing an OLE object starts the application used to create the object, allowing it to be edited.

If the DblClick event doesn't occur within the double-click time limit of the system, the form, form section, or control recognizes two Click events instead of a single DblClick event. The double-click time limit depends on the Double-click speed setting in the Mouse section of the Microsoft Windows Control Panel.

By running a macro or an event procedure when the DblClick event occurs, you can open a window or document when an icon is double-clicked.

Double-clicking a control causes both Click and DblClick events to occur. If the control doesn't already have the focus when you double-click it, the Enter and GotFocus events for the control occur before the Click and DblClick events.

For objects that receive mouse events, the events occur in this order:

MouseDown ⇒ MouseUp ⇒ Click ⇒ DblClick.

When you double-click a command button, the following events occur in this order:

MouseDown ⇒ MouseUp ⇒ Click ⇒ DblClick ⇒ MouseUp ⇒ Click

The second click may have no effect (for example, if the Click macro opens a modal dialog box in response to the first Click event). To prevent the second Click macro or event procedure from running, put a CancelEvent action in the DblClick macro or use the Cancel argument in the DblClick event procedure.

If you double-click any other control besides a command button, the second Click event doesn't occur.


DblClick Event - Macros
DblClick Event — Macros

To run a macro when the DblClick event occurs, set the OnDblClick property to the name of the macro.

Remarks

By running a macro when the DblClick event occurs, you can modify a control's default double-click behavior. For example, you can run a macro before an OLE application is opened in response to double-clicking an embedded object. The macro could display a message asking if the user wants to print or edit the object. You could use a user-defined function to print the object.

You can also use the DblClick event to enable a dialog box to be closed by double-clicking a control instead of clicking the OK button. The DblClick macro runs a Close action for the dialog box. You could also have the macro hide the dialog box by using the SetValue action to set the dialog box's Visible property to No.

You use the CancelEvent action in a DblClick macro to cancel the default double-click behavior of the control. If the user wanted to print the object mentioned earlier in this topic instead of editing it, you would use a user-defined function to print the object, and then use a CancelEvent action to cancel opening of the OLE application.

Note	When you double-click a command button, the following events occur in this order:

Click ⇒ DblClick ⇒ Click

The second click may have no effect (for example, if the Click macro opens a modal form). To prevent the second Click event from occurring, you can use the CancelEvent action in the DblClick macro. This sequence of Click, DblClick, Click events occurs when you double-click a command button only, not other types of controls.


DblClick Event - Event Procedures
DblClick Event — Event Procedures

To create an event procedure that is run when the DblClick event occurs, set the OnDblClick property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_DblClick (Cancel As Integer)

Private Sub controlname_DblClick (Cancel As Integer)

The DblClick event procedure uses the following arguments.

Argument	Description
controlname	A string that is the name of the control affected by the DblClick event procedure.
Cancel	The setting determines if the DblClick event occurs. Setting Cancel to True (-1) cancels the DblClick event.
Remarks

You can use a DblClick event procedure to modify a control's default double-click behavior. For example, you can have the event procedure execute in response to double-clicking an embedded object before an OLE application is opened. The event procedure could display a message asking if the user wants to print or edit the object. You could use a user-defined function to print the object. If the user decides to print the object instead of editing it, you could print the object, and then use the Cancel argument to cancel opening of the OLE application.

This event procedure is also useful for carrying out multiple steps with a single action, such as double-clicking to select an item in a list box or to close a dialog box. To carry out more than one command using a single action, you can use a DblClick event procedure for a list box in tandem with a command button whose Default property is set to True (-1). As part of the DblClick event procedure for the list box, you call the command button's Click event procedure.

When you create event procedures for MouseDown, MouseUp, Click, and DblClick events, make sure that their code doesn't conflict. (For example, the Click event procedure shouldn't contain code that cancels actions carried out in the DblClick event procedure.)

When you double-click a command button, the following events occur in this order:

Click ⇒ DblClick ⇒ Click

To prevent the second Click event from occurring, you can set the Cancel argument to True (-1) or use the CancelEvent method of the DoCmd object in the DblClick event procedure. If you don't cancel the second Click event, the code in the Click event procedure is run. The following example cancels the second Click event:

Private Sub CmdButton_DblClick (Cancel As Integer)
Cancel = True	' Cancel the second Click event.
End Sub


DblClick Event - Event Procedures Example
DblClick Event — Event Procedures Example

This example shows how you can use a DblClick event procedure to call a Click event procedure for a command button. When the user double-clicks the Products box, the Click event for the Close button is triggered when its Value property is set to True (-1). This causes the Close button's Click event procedure to run.

To try the following example, add the code to the Declarations section of a form named Main that contains a list box called Products.

Private Sub Products_DblClick (Cancel As Integer)
Close_Click	' Trigger Click event.
End Sub


Enter, Exit Events

These events occur:

Enter [image] before a control actually receives the focus from a control on the same form.

Exit [image] just before a control loses the focus to another control on the same form.

Notes

The Enter and Exit events apply only to controls on a form.

These events don't apply to check boxes, option buttons, or toggle buttons in an option group. They apply only to the option group itself.

Remarks

The Enter event occurs before the GotFocus event. The Exit event occurs before the LostFocus event.

Unlike GotFocus and LostFocus, the Enter and Exit events don't occur when a form receives or loses the focus. For example, suppose you select a check box on a form, and then click a report. The GotFocus and Enter events occur when you select the check box. Only the LostFocus event occurs when you click the report. The Exit event doesn't occur (because the focus is moving to a different window). If you select the check box on the form again to bring it to the foreground, the GotFocus event occurs, but not the Enter event (because the control had the focus when the form was last active). The Exit event occurs only when you click another control on the form.

If you move the focus on another form to a control that doesn't have the focus on that form, the Exit and LostFocus events for the control that does have the focus on the other form occur before the Enter and GotFocus events for the control you moved to.

If you use the mouse to move the focus from a control on a main form to a control on a subform of that form, the following events occur:

Exit (for the control on the main form)

 ⇓

LostFocus (for the control on the main form)

 ⇓

Enter (for the subform control)

 ⇓

Exit (for the control on the subform that had the focus)

 ⇓

LostFocus (for the control on the subform that had the focus)

 ⇓

Enter (for the control on the subform that the focus moved to)

 ⇓

GotFocus (for the control on the subform that the focus moved to)

If the control you move to on the subform previously had the focus, neither its Enter event nor its GotFocus event occurs, but the Enter event for the subform control does occur. If you move the focus from a control on a subform to a control on the main form, the Exit and LostFocus events for the control on the subform don't occur, just the Exit event for the subform control and the Enter and GotFocus events for the control on the main form.

Note   You often use the mouse or a key such as TAB to move the focus to another control. This causes mouse or keyboard events to occur in addition to the events discussed in this topic.

Because the Enter event occurs before the focus moves to a particular control, you can use an Enter macro or event procedure to display instructions; for example, you could use a macro or event procedure to display a small form or message box identifying the type of data the control typically contains.


Enter, Exit Events - Macros
Enter, Exit Events — Macros

To run a macro when the Enter or Exit event occurs, set the OnEnter or OnExit property to the name of the macro.

Remarks

When the Enter or Exit event occurs, you can run a macro that uses a GoToControl action to change the tab order based on current data in a control. For example, if the user enters Single in the MaritalStatus field, the focus won't move to the SpouseName field.

You can use the CancelEvent action in an Exit macro to cancel exiting the control. You can't use the CancelEvent action in an Enter macro. However, you can use the GoToControl action in an Enter macro to move the focus to a different control.


Enter, Exit Events - Event Procedures
Enter, Exit Events — Event Procedures

To create an event procedure that is run when the Enter or Exit event occurs, set the OnEnter or OnExit property to [Event Procedure], and click the Build button.

Syntax

Private Sub controlname_Enter ( )

Private Sub controlname_Exit (Cancel As Integer)

The Enter event procedure uses the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the event procedure.
The Exit event procedure uses the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the Exit event procedure.
Cancel	The setting determines if the Exit event occurs. Setting Cancel to True (-1) cancels the Exit event
Remarks

You can't cancel the Enter event.


Enter, Exit Events - Event Procedures Example
Enter, Exit Events — Event Procedures Example

In this example, two event procedures are attached to the LastName text box. The Enter event procedure displays a message specifying what type of data the user can enter in the text box. The Exit event procedure displays a dialog box asking the user if changes should be saved before the focus moves to another control. If the user chooses Cancel, the Cancel argument is set to True (-1), which moves the focus to the text box without saving changes. If the user chooses OK, the changes are saved, and the focus moves to another control.

To try the following example, add the code to the Declarations section of a form that contains a text box named CodeName.

Private Sub LastName_Enter ()
MsgBox "Enter your last name."
End Sub

Private Sub LastName_Exit (Cancel As Integer)

Dim strMsg As String

strMsg = "You entered '" & Me!LastName & "' as your last name." & _

vbCrLf & "Is this correct?"
If MsgBox(strMsg, vbYesNo) = vbNo Then
Cancel = True	' Cancel exit.
Else
Exit Sub	' Save changes and exit.
End If
End Sub


Format Event

The Format event occurs when Microsoft Access determines which data belongs in a report section, but before Microsoft Access formats the section for previewing or printing.

Remarks

A Format event occurs for each section in a report. This allows you to create complex running calculations using data from each section, including sections that aren't printed.

For report detail sections, the Format event occurs for each record in the section just before Microsoft Access formats the data in the record. A Format macro or event procedure has access to the data in the current record.

For report group headers, the Format event occurs for each new group, and a Format macro or event procedure has access to data in the group header and data in the first record in the detail section. For report group footers, the Format event occurs for each new group, and a Format macro or event procedure has access to the data in the group footer and the data in the last record in the detail section.

By running a macro or running an event procedure when the Format event occurs, you can use data in the current record to make changes to the report that affect page layout. For example, you can display or hide a congratulatory message next to a salesperson's monthly sales total in a sales report, depending on the sales total. After the control is displayed or hidden, Microsoft Access formats the section using the values of format properties, such as CanGrow, CanShrink, HideDuplicates, KeepTogether, and Visible.

For changes that don't affect page layout or for event procedures or macros that should run only after the data on a page has been formatted, such as a macro that prints page totals, use the Print event for the report section.

There are times when Microsoft Access must return to previous sections on a report to perform multiple formatting passes. When this happens, the Retreat event occurs as the report returns to each previous section, and the Format event occurs more than once for each section. You can run a macro or event procedure when the Retreat event occurs to undo any changes that you made when the Format event occurred for the section. This is useful when your Format macro or event procedure carries out actions, such as calculating page totals or controlling the size of a section, that you want to perform only once for each section.


Format Event - Macros
Format Event — Macros

To run a macro when the Format event occurs, set the OnFormat property to the name of the macro.

Remarks

You can use the FormatCount property to check whether the Format event has occurred more than once for a section. For example, if a section doesn't fit on one page and part of it moves to the next page of the report, the Format event occurs once for each page, and the FormatCount property is set to 2. You can check the FormatCount property setting to determine how many times a Format macro is run per section.

You can use the CancelEvent action in a Format macro to cancel formatting of a section. Microsoft Access doesn't format the section for printing and prints the next section instead. You can use CancelEvent to skip a section in a report without leaving a blank space on the page when the report is printed.


Format Event - Event Procedures
Format Event — Event Procedures

To create an event procedure that is executed when the Format event occurs, set the OnFormat property to [Event Procedure], and click the Build button.

Syntax

Private Sub sectionname_Format (Cancel As Integer, FormatCount As Integer)

The Format event procedure uses the following arguments.

Argument	Description
sectionname	A string that is the name of the section affected by the Format event procedure.
Cancel	The setting determines if the formatting of the section occurs. Setting the Cancel argument to True (-1) cancels formatting of the section.
FormatCount	An integer value that specifies whether the Format event has occurred more than once for a section. For example, if a section doesn't fit on one page and part of it moves to the next page of the report, the FormatCount argument is set to 2.
Remarks

If you cancel formatting, Microsoft Access doesn't format the section for printing and prints the next section instead. You can use this event procedure to skip a section in a report without leaving a blank space on the page when the report is printed.


Format Event - Event Procedures Example
Format Event — Event Procedures Example

This example displays or hides a congratulatory message next to a calculated control that shows sales totals by salesperson. In report sections where the sales total is greater than the sales goal, a label named Message displays the message "Congratulations!  You have met your sales goal" before the section is printed; in sections where the sales total is less than the sales goal, the label is hidden.

To try the following example, add the following code to a report that contains a label called Message and a text box called GrandTotal.

Private Sub SalesDetail_Format (Cancel As Integer, _

FormatCount As Integer)
Const conSalesGoal = 1000

If Me!GrandTotal > conSalesGoal Then
Me!Message.Visible = True
Else
Me!Message.Visible = False
End If
End Sub


Open, Close Events

These events occur:

Open [image] for forms, the Open event occurs when a form is opened, but before the first record is displayed. For reports, the event occurs before a report is previewed or printed.

Close [image] occurs when a form or report is closed and removed from the screen.

Remarks

By running a macro or an event procedure when a form's Open event occurs, you can close another window or move the focus to a particular control on a form. You can also run a macro or an event procedure that asks for information needed before the form or report is opened or printed. For example, an Open macro or event procedure can open a custom dialog box in which the user enters the criteria for the set of records to display on a form or the date range to include for a report.

The Open event doesn't occur when you open a form that's already open [image] for example, when you switch to the form from another window in Microsoft Access or use the OpenForm action in a macro to bring the open form to the top.

When you open a form, Microsoft Access runs the underlying query for the form before it runs the Open macro or event procedure. However, when you open a report, Microsoft Access runs the Open macro or event procedure before it runs the underlying query for the report. This enables the user to specify criteria for the report before it opens [image] for example, in a custom dialog box you display when the Open event occurs.

If your application can have more than one form loaded at a time, use the Activate and Deactivate events instead of the Open event to display and hide custom toolbars when the focus moves to a different form.

The Open event occurs before the Load event, which is triggered when a form is opened and its records are displayed.

When you first open a form, the following events occur in this order:

Open ⇒ Load ⇒ Resize ⇒ Activate ⇒ Current

The Close event occurs after the Unload event, which is triggered after the form is closed but before it is removed from the screen.

When you close a form, the following events occur in this order:

Unload ⇒ Deactivate ⇒ Close

When you close a report, the following events occur in this order:

Unload ⇒ Close ⇒ Deactivate

When the Close event occurs, you can open another window or request the user's name to make a log entry indicating who used the form or report.

If you're trying to decide whether to use the Open or Load event for your macro or event procedure, one significant difference is that the Open event can be canceled, but the Load event can't. For example, if you're dynamically building a record source for a form in an event procedure for the form's Open event, you can cancel opening the form if there are no records to display. Similarly, the Unload event can be canceled, but the Close event can't.


Open, Close Events - Macros
Open, Close Events — Macros

To run a macro when the Open or Close event occurs, set the OnOpen or OnClose property to the name of the macro.

Remarks

You can use the CancelEvent action in an Open macro to cancel opening of the form or report. You can't use the CancelEvent action in a Close macro. However, you can use the CancelEvent action in a macro that runs when the Unload event occurs on a form. This cancels closing of the form.

If you want to refer to controls from an Open macro, you must first move the focus to the appropriate control or record. For example, to use a SetValue action in an Open macro to set the value of a control on a form, you must first use the GoToControl or GoToRecord action to access the control or the record containing the control.


Open, Close Events - Event Procedures
Open, Close Events — Event Procedures

To create an event procedure that is run when the Open or Close event occurs, set the OnOpen or OnClose property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Open (Cancel As Integer)

Private Sub Report_Open (Cancel As Integer)

Private Sub Form_Close ( )

Private Sub Report_Close ( )

The Open event procedure uses the following argument.

Argument	Description
Cancel	The setting determines if the opening of a form or report occurs. Setting Cancel to True (-1) cancels the opening of a form or report.
Remarks

You can't cancel the Close event.

If you want to refer to controls in an Open event procedure, you must first move the focus to the appropriate control or record using the SetFocus method or the GoToRecord or GoToControl method of the DoCmd object.

If an application has only one form loaded at a time, you can place code for displaying or hiding a toolbar in the Open event procedure for a form. The following example displays the toolbar MyToolbar when the form is opened:

Sub Form_Open(Cancel As Integer)
DoCmd.ShowToolbar "MyToolbar", acToolbarYes
End Sub


Open, Close Events - Event Procedures Example
Open, Close Events — Event Procedures Example

This example shows how you can cancel the opening of a form when the user chooses a Cancel button. A message box prompts the user to enter order details. If the user chooses Cancel, the Order Details form isn't opened.

To try the following example, add the following code to the Declarations section of a form.

Private Sub Form_Open (Cancel As Integer)
Dim intReturn As Integer

intReturn = MsgBox("Enter order details now?", vbYesNoCancel)

Select Case intReturn
Case vbYes
DoCmd.OpenForm "Order Details"	' Open Order Details form.
Case vbNo
MsgBox "Remember to enter order details by 5pm."
Case vbCancel
Cancel = True	' Cancel Open event.
End Select

End Sub


Print Event

The Print event occurs when data in a report section is formatted for printing, but before the section is printed.

Remarks

For a report detail section, the Print event occurs for each record in the section just before Microsoft Access prints the data in the record. A Print event procedure or macro has access to data in the current record.

For report group headers, the Print event occurs for each new group, and a Print macro or event procedure has access to data in the group header and the first record in the detail section. For report group footers, the Print event occurs for each new group, and a Print macro or event procedure has access to data in the group footer and the data in the last record in the detail section.

You can use the Print event to run a macro or execute an event procedure only after Microsoft Access has prepared data for printing on a page. For example, you can calculate running page totals that are printed in the page header or footer.

For changes that affect page layout, such as displaying or hiding controls, use the Format event.

The Print event occurs only for sections that are actually printed. If you need access to data from sections that aren't printed (for example, you are keeping a running sum, but are only printing certain pages), use the Format event instead.

The Page event occurs after all the Format events for the report, and after all the Print events for a page, but before the page is actually printed.


Print Event - Macros
Print Event — Macros

To run a macro when the Print event occurs, set the OnPrint property to the name of the macro.

Remarks

You can use the PrintCount property to check whether the Print event has occurred more than once for a record. For example, if part of a record is printed on one page and the rest is printed on the next page, the Print event occurs twice, and the PrintCount property is set to 2. You can check the PrintCount value for Print macros that should run only once for a record, such as a macro that shows totals for the records on a page in a page footer.

You can use the CancelEvent action in a Print macro to cancel printing of a section. Microsoft Access prints a blank area on the page where the section would have been when the report is printed. You can use CancelEvent to skip a record in a report and leave a blank area on the page in its place when the report is printed.

A Print macro runs only for sections that are actually printed.

Note   You can't use a Print macro to set properties for any object.


Print Event - Event Procedures
Print Event — Event Procedures

To create an event procedure that is run when the Print event occurs, set the OnPrint property to [Event Procedure], and click the Build button.

Syntax

Private Sub sectionname_Print (Cancel As Integer, PrintCount As Integer)

The Print event procedure uses the following arguments.

Argument	Description
sectionname	A string that is the name of the section affected by the Print event procedure.
Cancel	The setting determines if the printing of the section occurs. Setting the Cancel argument to True (-1) cancels printing of the section.
PrintCount	An integer value that specifies whether the Print event has occurred more than once for a record. For example, if part of a record is printed on one page and the rest is printed on the next page, the Print event occurs twice, and the PrintCount argument is set to 2.
Remarks

To cancel printing of the section, you set the Cancel argument to True (-1) or use the CancelEvent method of the DoCmd object. Microsoft Access prints a blank area on the page where the section would have been. You can use CancelEvent to skip a record in a report and leave a blank area on the page in its place when the report is printed.

Note   You can't use a Print event procedure to set properties for any object.


Print Event - Event Procedure Example
Print Event — Event Procedures Example

This example checks the PrintCount argument to determine the number of times the Print event has occurred. If it has occurred more than once, the Print event is canceled for the section.

To try the following example, add the following code to the Declarations section of a report that contains a section named CustomerDetail.

Private Sub CustomerDetail_Print (Cancel As Integer, _

PrintCount As Integer)
If PrintCount > 1 Then Cancel = True
End Sub


Current Event

The Current event occurs when the focus moves to a record, making it the current record, or when the form is requeried.

Remarks

This event occurs both when a form is opened and whenever the focus leaves one record and moves to another. Microsoft Access runs the Current macro or event procedure before the first or next record is displayed.

By running a macro or executing an event procedure when a form's Current event occurs, you can display a message or synchronize records in another form related to the current record. For example, when a customer record becomes current, you can display the customer's previous order. When a supplier record becomes current, you can display the products manufactured by the supplier in a Suppliers form. You can also perform calculations based on the current record or change the form in response to data in the current record.

If your macro or event procedure performs a GoToControl or GoToRecord action in response to an Open event, the Current event occurs.

The Current event also occurs when you refresh a form or requery the form's underlying table or query [image] for example, when you choose Remove Filter/Sort from the Records menu or use the Requery action in a macro or the Requery method in Visual Basic code.

When you first open a form, the following events occur in this order:

Open ⇒ Load ⇒ Resize ⇒ Activate ⇒ Current


Current Event - Macros
Current Event — Macros

To run a macro when the Current event occurs, set the OnCurrent property to the name of the macro.

Remarks

You can use a Current macro to display a message or synchronize records in another form related to the current record. For example, when a customer record becomes current, a macro can display the customer's previous order. When a supplier record is current, the macro can display the products manufactured by the supplier in a Suppliers form.

You can't use the CancelEvent action in a Current macro. However, you can use the GoToRecord action to move the focus to a different record.


Current Event - Event Procedures
Current Event — Event Procedures

To create an event procedure that is run when the Current event occurs, set the OnCurrent property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Current ( )

Remarks

You can't cancel this event using the CancelEvent method of the DoCmd object. However, you can use the GoToRecord method of the DoCmd object to move to a different record.


Current Event - Event Procedures Examples
Current Event — Event Procedures Examples

In the following example, a Current event procedure checks the status of an option button called Discontinued. If the user selects the button, the example runs a query to determine substitute products.

Private Sub Form_Current ()
If Me!Discontinued.Value = True Then
.	' Code to run query.

.

.

EndIf
End Sub

The following example sets a form's Caption property to the SupplierName field. As the focus moves from record to record, the title bar displays the current supplier name.

Private Sub Form_Current ()
Me.Caption = Me!SupplierName.Value
End Sub


Delete, BeforeDelConfirm, AfterDelConfirm Events

These events occur:

Delete [image] when the user performs some action, such as pressing the DEL key, to delete a record, but before the record is actually deleted.

BeforeDelConfirm [image] after the user deletes one or more records, but before Microsoft Access displays a dialog box asking the user to confirm the deletions.

AfterDelConfirm [image] after the user confirms the deletions and the records are actually deleted or when the deletions are canceled.

Remarks

After a record is deleted, it's stored in a temporary buffer. The BeforeDelConfirm event occurs after the Delete event (or if you've deleted more than one record, after all the records are deleted), but before the delete confirm dialog box is displayed. Canceling the BeforeDelConfirm event restores a record from the buffer and prevents the delete confirm dialog box from being displayed.

The AfterDelConfirm event occurs after a record is actually deleted or after a deletion is canceled. If the BeforeDelConfirm event isn't canceled, the AfterDelConfirm event occurs after the delete confirm dialog box is displayed. The AfterDelConfirm event occurs even if the BeforeDelConfirm event is canceled. The AfterDelConfirm event procedure returns status information about the deletion. You can use a macro or event procedure associated with the AfterDelConfirm event to recalculate totals affected by the deletion of records.

If you cancel the Delete event, the BeforeDelConfirm and AfterDelConfirm events don't occur and the delete confirm dialog box isn't displayed.

By running a macro or executing an event procedure when the Delete event occurs, you can prevent a record from being deleted or allow a record to be deleted only under certain conditions. You can also use a Delete event to display a dialog box asking whether the user wants to delete a record before it's deleted.

To delete a record, you must first click the record selector or choose Select Record from the Edit menu to select the record. If you click the record selector of the current record or choose Select Record, the Exit and LostFocus events for the control that has the focus occur. If you've changed any data in the record, the BeforeUpdate and AfterUpdate events for the record occur before the Exit and LostFocus events. If you click the record selector of a different record, the Current event for that record also occurs.

After you delete the record, the focus moves to the next record following the deleted record, and the Current event for that record occurs, followed by the Enter and GotFocus events for the first control in that record.

The BeforeDelConfirm event then occurs, just before Microsoft Access displays a dialog box asking you to confirm the deletion. After you respond to the dialog box (or after the deletion is confirmed or canceled), the AfterDelConfirm event occurs. (However, the BeforeDelConfirm and AfterDelConfirm events don't occur and the deletion confirmation dialog box isn't displayed if you set the Confirm Record Changes option in the Edit/Find tab of the Options dialog box to No.)

You can delete one or more records at a time. The Delete event occurs after each record is deleted. This enables you to access the data in each record before it's actually deleted, and selectively confirm or cancel each deletion in the Delete macro or event procedure. When you delete more than one record, the Current event for the record following the last deleted record and the Enter and GotFocus events for the first control in this record don't occur until all the records are deleted. In other words, a Delete event occurs for each selected record, but no other events occur until all the selected records are deleted. The BeforeDelConfirm and AfterDelConfirm events also don't occur until all the selected records are deleted.


Delete, BeforeDelConfirm, AfterDelConfirm Events - Macros
Delete, BeforeDelConfirm, AfterDelConfirm Events — Macros

To run a macro when a Delete, BeforeDelConfirm, or AfterDelConfirm event occurs, set the OnDelete, BeforeDelConfirm, or AfterDelConfirm property to the name of the macro.

Remarks

You can use a Delete macro to display a dialog box asking whether the user wants to delete a record before it's deleted.

You can use a BeforeDelConfirm or AfterDelConfirm macro to respond whenever the user deletes a record. However, the BeforeDelConfirm and AfterDelConfirm macros can't set the argument determining whether the delete confirm dialog box is displayed and can't return the argument indicating the status of the deletion, so you typically use event procedures with these events.

You can use the CancelEvent action in a Delete macro to cancel the deletion.

You can use the CancelEvent action in a BeforeDelConfirm macro to cancel the deletion of all the deleted records. If you do this, the delete confirm dialog box isn't displayed. However, the AfterDelConfirm event occurs even if you cancel the BeforeDelConfirm event.

You can't use the CancelEvent action in an AfterDelConfirm macro.


Delete, BeforeDelConfirm, AfterDelConfirm Events - Event Procedures
Delete, BeforeDelConfirm, AfterDelConfirm Events — Event Procedures

To create an event procedure that is run when a Delete, BeforeDelConfirm, or AfterDelConfirm event occurs, set the OnDelete, BeforeDelConfirm, or AfterDelConfirm property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_Delete (Cancel As Integer)

Private Sub Form_BeforeDelConfirm (Cancel As Integer, Response As Integer)

Private Sub Form_AfterDelConfirm (Status As Integer)

The Delete event procedure uses the following argument.

Argument	Description
Cancel	The setting determines if the Delete event occurs. Setting Cancel to True (-1) cancels the Delete event.
The BeforeDelConfirm event procedure uses the following arguments.

Argument	Description
Cancel	The setting determines if the BeforeDelConfirm event occurs. Setting Cancel to True (-1) cancels the BeforeDelConfirm event and prevents the delete confirm dialog box from being displayed. If the event is canceled, the original records are restored, but the AfterDelConfirm event still occurs. If Cancel is set to True (-1), the Response argument is ignored.
	Setting Cancel is set to False (0), does not cancel the BeforeDelConfirm event and the value in the Response argument is used by Microsoft Access to determine the type of response to the delete event.
Response	An intrinsic constant that determines whether Microsoft Access displays a dialog box asking if the record should be deleted. The Response argument can have the following constants.
Constant	Description
acDataErrContinue	Enables Microsoft Access to delete records without prompting the user.
acDataErrDisplay	Displays the default message.
The AfterDelConfirm event procedure uses the following argument.

Argument	Description
Status	An intrinsic constant that determines whether a record has been deleted. The Status argument can be any the following constants:
Constant	Description
acDeleteOK	Indicates the deletion was successful.
acDeleteCancel	Indicates the deletion was canceled in Visual Basic.
acDeleteUserCancel	Indicates the deletion was canceled by the user.
Remarks

The AfterDelConfirm event can't be canceled.

You can use these events to customize how records are deleted. For example, when a user deletes a record, such as an employee record, the Delete event occurs. You can place code in the Delete event procedure to save the data from the Employee ID and Name fields in a temporary buffer. When the BeforeDelConfirm event occurs, you can prevent the delete confirm dialog box from being displayed by setting the Response argument to acDataErrContinue. This enables you to display a custom dialog box. When the AfterDelConfirm event occurs and the Status argument is set to acDeleteOK, you can do the actual delete in the table and clear the record from the temporary buffer.


Delete, BeforeDelConfirm, AfterDelConfirm Events - Event Procedures Examples
Delete, BeforeDelConfirm, AfterDelConfirm Events — Event Procedures Examples

This example shows how you can prevent a user from deleting records from a table.

To try this example, add the following code to the Declarations section of a form that is based on an Employees table. Switch to the form's Datasheet view and try to delete a record.

Private Sub Form_Delete (Cancel As Integer)
Cancel = True
MsgBox "This record can't be deleted."
End Sub

The following example shows how you can use the BeforeDelConfirm event procedure to suppress the default confirmation dialog box and display a custom dialog box when a record is deleted. It also shows how you can use the AfterDelConfirm event procedure to display a message indicating whether the deletion progressed in the usual way or whether it was canceled in Visual Basic or by the user.

To try this example, add the following code to the Declarations section of a form that is based on a table or query.

Private Sub Form_BeforeDelConfirm (Cancel As Integer, _

Response As Integer)
' Suppress default delete confirm dialog box.

Response = acDataErrContinue

' Display custom dialog box.
If MsgBox ("Delete this record?", vbOKCancel) = vbCancel Then
Cancel = True

End If
End Sub

Private Sub Form_AfterDelConfirm (Status As Integer)
Select Case Status
Case acDeleteOK
MsgBox "Deletion occurred normally."
Case acDeleteCancel
MsgBox "Programmer canceled the deletion."
Case acDeleteUserCancel
MsgBox "User canceled the deletion."
End Select
End Sub


BeforeInsert, AfterInsert Events

These events occur:

BeforeInsert [image] when the user types the first character in a new record, but before the record is actually created.

AfterInsert [image] after a new record is added.

Note   Setting the value of a control using a macro or Visual Basic doesn't trigger these events.

Remarks

You can use an AfterInsert event procedure or macro to requery a recordset whenever a new record is added.

The BeforeInsert and AfterInsert events are similar to the BeforeUpdate and AfterUpdate events. These events occur in the following order:

BeforeInsert ⇒ BeforeUpdate ⇒ AfterUpdate ⇒ AfterInsert.

The following table summarizes the interaction between these events.

Event	Occurs when
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.


BeforeInsert, AfterInsert Events - Macros
BeforeInsert, AfterInsert Events — Macros

To run a macro when the BeforeInsert or AfterInsert event occurs, set the BeforeInsert or AfterInsert property to the name of the macro.

Remarks

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.


BeforeInsert, After Insert Events - Event Procedures
BeforeInsert, AfterInsert Events — Event Procedures

To create an event procedure that is executed when the BeforeInsert or AfterInsert event occurs, set the BeforeInsert or AfterInsert property to [Event Procedure], and click the Build button.

Syntax

Private Sub Form_BeforeInsert (Cancel As Integer)

Private Sub Form_AfterInsert ( )

The BeforeInsert event procedure uses the following argument

Argument	Description
Cancel	The setting determines if the BeforeInsert event occurs. Setting Cancel to True (-1) cancels the BeforeInsert event.
Remarks

You can't cancel the AfterInsert event.


BeforeInsert, AfterInsert Events - Event Procedures Example
BeforeInsert, AfterInsert Events — Event Procedures Example

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 this example, add the following code to the Declarations section of a form named Employees that is based on a table or query. Switch to the form's 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


Updated Event

The Updated event occurs when an OLE object's data has been modified.

Note   The Updated event applies only to controls on a form, not controls on a report.

Remarks

You can use this event to determine if an object's data has been changed since it was last saved.

The Updated event occurs when the data in an OLE object has been modified. This update can come from the application in which the object was created or from one of the linked copies of this object. As a result, this event is asynchronous with other Microsoft Access control events.

Note   The Updated event and the BeforeUpdate and AfterUpdate events for bound and unbound object frames are not related. The Updated event occurs when an OLE object's data is changed, and the BeforeUpdate and AfterUpdate events occur when data is updated. Although not related, all three events usually occur when an OLE object's data is changed. The Updated event generally occurs before the BeforeUpdate and AfterUpdate events; however, this may not happen every time.


Updated Event - Macros
Updated Event — Macros

To run a macro when the Updated event occurs, set the OnUpdated property to the name of the macro.

Remarks

You can use an Updated macro to display a message whenever an OLE object's data has been updated. However, macros can't return the code that determines how the OLE object was updated, so you typically use event procedures with this event.

You can't use the CancelEvent action in an Updated macro.


Updated Event - Event Procedures
Updated Event — Event Procedures

To create an event procedure that is run when the Updated event occurs, set the OnUpdated property to [Event Procedure], and click the Build button.

To see if an object's data has been changed since it was last saved, set a global variable in the Updated event procedure indicating that the object needs to be saved. When you save the OLE object, reset the variable.

Syntax

Private Sub controlname_Updated (Code As Integer)

The Updated event procedure uses the following argument.

Argument	Description
controlname	A string that is the name of the control affected by the Updated event procedure.
Code	An intrinsic constant that indicates how the OLE object was updated. The Code argument can have the following constants:
Constant	Description
acOLEChanged	Indicates that the object's data has changed.
acOLESaved	Indicates that the object's data has been saved by the application that created the object. This usually occurs when the user chooses the application's Update command or whatever command is used for updating.
acOLEClosed	Indicates that the file containing the object's data has been closed by the application that created the object.
acOLERenamed	Indicates that the file containing the object's data has been renamed by the application that created the object.


NotInList Event

The NotInList event occurs when the user enters a value in the text box portion of a combo box that isn't in the combo box list.

Note   The NotInList event applies only to controls on a form, not controls on a report.

Remarks

This event enables the user to add a new value to the combo box list.

The LimitToList property must be set to Yes for the NotInList event to occur.

The NotInList event doesn't trigger the Error event.

The NotInList event occurs for combo boxes whose LimitToList property is set to Yes after you enter a value that is not in the list and attempt to move to another control or save the record. It occurs after all the Change events for the combo box.


NotInList Event - Macros
NotInList Event — Macros

To run a macro when the NotInList event occurs, set the OnNotInList property to the name of the macro.

Remarks

You can use a NotInList macro to add a new value to the combo box list. When the NotInList event occurs, open a custom dialog box and set the value of one of its controls to the new value. This control should be bound to the field in the table or query that is the source for the combo box. Save the record in the custom dialog box, then requery the combo box.

You can't use the CancelEvent action in a NotInList macro.


NotInList Event - Event Procedures
NotInList Event — Event Procedures

To create an event procedure that is executed when the NotInList event occurs, set the OnNotInList property to [Event Procedure], and click the Build button.

Syntax

Private Sub controlname_NotInList (NewData As String, Reponse As Integer)

The NotInList event procedure uses the following arguments

Argument	Description
controlname	A string that is the name of the control affected by the NotInList event procedure.
NewData	A string that Microsoft Access uses to pass the text the user entered in the text box portion of the combo box to the event procedure.
Response	An intrinsic constant that indicates how the NotInList event was handled. The Response argument can have the following constants.
Constant	Description
acDataErrDisplay	(Default) Displays the default message to the user. You can use this when you don't want to allow the user to add a new value to the combo box list.
acDataErrContinue	Doesn't display the default message to the user. You can use this when you want to display a custom message to the user. For example, the event procedure could display a custom dialog box asking if the user wanted to save the new entry. If the response is Yes, the event procedure would add the new entry to the list and set the Response argument to acDataErrAdded. If the response is No, the event procedure would set the Response argument to acDataErrContinue.
acDataErrAdded	Doesn't display a message to the user but enables you to add the entry to the combo box list in the NotInList event procedure. After the entry is added, Microsoft Access updates the list by requerying the combo box. Microsoft Access then rechecks the string against the combo box list, and saves the value in NewData in the field the combo box is bound to. If the string is not in the list, then Microsoft Access displays an error message.
Remarks

You can create an event procedure for the NotInList event that provides a way for the user to add a new item to the combo box list. For example, you can add a record to the table that supplies the list's values, or add a value to the value list that is the source for the combo box list.

To add a new entry to a combo box list, your event procedure must add the value in the NewData argument to the source of the combo box list. How you do this depends on the type of source the combo box list uses, as determined by the RowSourceType and RowSource properties of the combo box. In the Example in this topic, the event procedure adds the new value to a value list for the combo box.

If you let the user change the value originally typed in the combo box (for example, in a custom dialog box), you must set the combo box value to the new entry entered in the custom dialog box. This saves the new value in the field the combo box is bound to. Set the Response argument to acDataErrContinue, and Microsoft Access will add the new value to the combo box list.


NotInList Event - Event Procedures Example
NotInList Event — Event Procedures Example

The following example uses the NotInList event to add an item to a combo box.

To try this example, create a combo box called Colors on a form. Set the LimitToList property of the combo box to Yes. To populate the combo box, set the RowSourceType property of the combo box to Value List, and supply a list of values separated by semicolons as the setting for the RowSource property. For example, you might supply the following values as the setting for this property: Red; Green; Blue.

Next add the following code to the Declarations section of the form. Switch to Form view and enter a new value in the text portion of the combo box.

Private Sub Colors_NotInList(NewData As String, _

Response As Integer)

Dim ctl As Control

' Return Control object that points to combo box.

Set ctl = Me!Colors

' Prompt user to verify they wish to add new value.

If MsgBox("Value is not in list. Add it?", vbOKCancel) = vbOK Then

' Set Response argument to indicate that data is being added.

Response = acDataErrAdded

' Add string in NewData argument to row source.

ctl.RowSource = ctl.RowSource & ";" & NewData

Else

' If user chooses Cancel, suppress error message and undo changes.

Response = acDataErrContinue

ctl.Undo

End If

End Sub

Note   The above example adds an item to an unbound combo box. When you add an item to a bound combo box, you add a value to a field in the underlying data source. In most cases you can't simply add one field in a new record [image] depending on the structure of data in the table, you probably will need to add one or more fields to fulfill data requirements. For instance, a new record must include values for any fields comprising the primary key. If you need to add items to a bound combo box dynamically, you must prompt the user to enter data for all required fields, save the new record, and then requery the combo box to display the new value.


CodeDb Function

You can use the CodeDb function in a module to determine the name of the Database object that refers to the database in which code is currently executing. Use the CodeDb function to access data access objects that are part of a library database.

For example, you can use the CodeDb function in a module in a library database to create a Database object referring to the library database. You can then open a recordset based on a table in the library database.

Syntax

Set database = CodeDb

The CodeDb function has the following argument.

Argument	Description

database	A Database object variable.

Remarks

The CodeDb function returns a Database object for which the Name property is the full path name of the database from which it is called. This function can be useful when you need to manipulate the data access objects in your library database.

When you call a function in a library database, the database from which you have called the function remains the current database, even while code is executing in a module in the library database. In order to refer to the data access objects in the library database, you need to know the name of the Database object that represents the library database.

For instance, suppose you have a table in a library database that lists error messages. To manipulate data in the table from code, you could use the CodeDb function to determine the name of the Database object that refers to the library database that contains the table.

If the CodeDb function is executed from the current database, it returns the name of the current database, which is the same value returned by the CurrentDb function.


CodeDb Function Example

The following example uses the CodeDb function to return a Database object that refers to a library database. The library database contains both a table named Errors and the code that is currently executing. After the CodeDb function determines this information, the GetErrorString function opens a table-type recordset based on the Errors table. It then extracts an error message from a field named ErrorData based on the integer value passed to the function.

Function GetErrorString (ByVal intError As Integer) As String

Dim dbs As Database, rst As RecordSet

' Variable refers to database where code is executing.

Set dbs = CodeDb

' Create table-type Recordset.

Set rst = dbs.OpenRecordSet("Errors", dbOpenTable)

' Set index to primary key (ErrorID field).

rst.Index = "PrimaryKey"

' Find error number passed into GetErrorString.

rst.Seek "=", intError

' Return associated error message.

GetErrorString = rst.Fields!ErrorData.Value

rst.Close

End Function


CreateControl, CreateReportControl Functions

You can use the CreateControl function to create a control on a specified open form. You can use the CreateReportControl function to create a control on a specified open report.

For example, suppose you are building a custom wizard that allows users to easily construct a particular form. You can use the CreateControl function in your wizard to add the appropriate controls to the form.

Syntax

CreateControl(formname, controltype[, section[, parent[, columnname[, left[, top[, width[, height]]]]]]])

CreateReportControl(reportname, controltype[, section[, parent[, columnname[, left[, top[, width[, height]]]]]]])

The CreateControl and CreateReportControl functions take the following arguments.

Argument	Description

formname, reportname	A string expression identifying the name of the open form or report on which you want to create the control.

controltype	One of the following intrinsic constants identifying the type of control you want to create. You can view these constants and paste them into your code from the Object Browser. Click the Object Browser button. Then click Access in the Libraries/Databases box, and click Constants in the Modules/Classes box.

Constant	Value	Control
acLabel	100	Label
acRectangle	101	Rectangle
acLine	102	Line
acImage	103	Image
acCommandButton	104	Command button
acOptionButton	105	Option button
acCheckBox	106	Check box
acOptionGroup	107	Option group
acBoundObjectFrame	108	Bound object frame
acTextBox	109	Text box
acListBox	110	List box
acComboBox	111	Combo box
acSubform	112	Subform
acObjectFrame	114	Unbound object frame
acPageBreak	118	Page break
acCustomControl	119	Custom control
acToggleButton	122	Toggle button
section	One of the following intrinsic constants identifying the section that will contain the new control.

Constant	Section
acDetail	(Default) Detail section
acHeader	Form or report header
acFooter	Form or report footer
acPageHeader	Page header
acPageFooter	Page footer
acGroupLevel1Header	Group-level 1 header (reports only)
acGroupLevel1Footer	Group-level 1 footer (reports only)
acGroupLevel2Header	Group-level 2 header (reports only)
acGroupLevel2Footer	Group-level 2 footer (reports only)
If a report has additional group levels, the header/footer pairs are numbered consecutively, beginning with 9.

parent	String expression identifying the name of the parent control of an attached control. For controls that have no parent control, use a zero-length string for this argument.

columnname	Name of the field to which the control will be bound, if it is to be a data-bound control.

If you are creating a control that will not be bound to a field, use a zero-length string for this argument.

left, top	Numeric expressions indicating the coordinates for the upper-left corner of the control in twips.

width, height	Numeric expressions indicating the width and height of the control in twips.

Remarks

Use the CreateControl and CreateReportControl functions in a custom wizard to create controls on a form or report. Both functions return a Control object.

You can use the CreateControl and CreateReportControl functions only in form Design view or report Design view, respectively.

You use the parent argument to identify the relationship between a main control and a subordinate control. For example, if a text box has an attached label, the text box is the main (or parent) control and the label is the subordinate (or child) control. When you create the label control, set its parent argument to a string identifying the name of the parent control. When you create the text box, set its parent argument to a zero-length string.

You also set the parent argument when you create check boxes, option buttons, or toggle buttons. An option group is the parent control of any check boxes, option buttons, or toggle buttons that it contains. The only controls that can have a parent control are a label, check box, option button, or toggle button. All of these controls can also be created independently, without a parent control.

Set the columnname argument according to the type of control you are creating and whether or not it will be bound to a field in a table. The controls that may be bound to a field include the text box, list box, combo box, option group, and bound object frame. Additionally, the toggle button, option button, and check box controls may be bound to a field if they are not contained in an option group.

If you specify the name of a field for the columnname argument, you create a control that is bound to that field. All of the control's properties are then automatically set to the settings of any corresponding field properties. For example, the value of the control's ValidationRule property will be the same as the value of that property for the field.

Tip   If your wizard creates controls on a new or existing form or report, it must first open the form or report in Design view.

To remove a control from a form or report, use the DeleteControl and DeleteReportControl statements.


CreateControl, CreateReportControl Functions Example

The following example first creates a new form based on an Orders table. It then uses the CreateControl function to create a text box control and an attached label control on the form.

Sub NewControls()
Dim frm As Form

Dim ctlLabel As Control, ctlText As Control

Dim intDataX As Integer, intDataY As Integer

Dim intLabelX As Integer, intLabelY As Integer

' Create new form with Orders table as its record source.

Set frm = CreateForm
frm.RecordSource = "Orders"

' Set positioning values for new controls.

intLabelX = 100
intLabelY = 100
intDataX = 1000

intDataY = 100

' Create unbound default-size text box in detail section.

Set ctlText = CreateControl(frm.Name, acTextBox, , "", "", _

intDataX, intDataY)
' Create child label control for text box.

Set ctlLabel = CreateControl(frm.Name, acLabel, , ctlText.Name, _

"NewLabel", intLabelX, intLabelY)

' Restore form.

DoCmd.Restore

End Sub


CreateForm, CreateReport Functions

The CreateForm function creates a form and returns a Form object. The CreateReport function creates a report and returns a Report object.

For example, suppose you are building a custom wizard to create a sales report. You can use the CreateReport function in your wizard to create a new report based on a specified report template.

Syntax

CreateForm([database[, formtemplate]])

CreateReport([database[, reporttemplate]])

The CreateForm and CreateReport functions take the following arguments.

Argument	Description

database	A string expression identifying the name of the database that contains the form or report template you want to use to create a form or report. If you omit this argument, the current database (the value returned by the CurrentDb function) is used.

formtemplate, reporttemplate	A string expression identifying the name of the form or report you want to use as a template to create a new form or report. To create a form or report based on the default template, set this argument to Normal. If you omit this argument, Microsoft Access bases the new form or report on the template specified by the Forms/Reports tab of the Options dialog box, available by clicking Options on the Tools menu.

Remarks

Use the CreateForm and CreateReport functions when designing a wizard that creates a new form or report.

The CreateForm and CreateReport functions open a new, minimized form or report in form Design view or report Design view, respectively.

The form or report you specify for formtemplate or reporttemplate can be a form or report that you have created specifically to be used as a template, or any other form or report in the database identified by the database argument.

If the name you use for the formtemplate or reporttemplate argument isn't valid, Visual Basic uses the form or report template specified by the Form Template or Report Template setting in the Forms/Reports tab of the Options dialog box, available by clicking Options on the Tools menu.

CreateForm and CreateReport create minimized forms and reports.

Note   If you have created a form or report template in another database, the name of that template will be displayed in the Form Template or Report Template options in the Forms/Reports tab of the Options dialog box for every database created in Microsoft Access. In order to create a form or report based on a template that is not in your current database, however, you must either specify the other database in the database argument, or specifically import the template into the current database.


CreateForm, CreateReport Functions Example

The following example creates a report in the current database using the template specified by the Report Template setting in the Forms/Reports tab of the Options dialog box.

Sub NormalReport()
Dim rpt As Report

Set rpt = CreateReport	' Create minimized report.
DoCmd.Restore	' Restore report.

End Sub

The next example creates a new form in the Northwind sample database based on the Customers form, and sets its RecordSource property to the Customers table. Run this code from the Northwind sample database.

Sub NewForm()

Dim frm as Form

' Create form based on Customers form.

Set frm = CreateForm("Northwind.mdb", "Customers")

DoCmd.Restore

' Set RecordSource to Customers table.

frm.RecordSource = "Customers"

End Sub


CreateGroupLevel Function

You can use the CreateGroupLevel function to specify a field or expression on which to group or sort data in a report.

For example, suppose you are building a custom wizard that provides the user with a choice of fields on which to group data when designing a report. Call the CreateGroupLevel function from your wizard to create the appropriate groups according to the user's choice.

Syntax

CreateGroupLevel(report, expression, header, footer)

The CreateGroupLevel function syntax has the following arguments.

Argument	Description

report	A string expression identifying the name of the report that will contain the new group level.

expression	A string expression identifying the field or expression to sort or group on.

header, footer	An integer value that indicates whether a field or expression will have an associated group header and/or footer. If header and/or footer is True (-1), the field or expression will have a group header and/or footer. If header and/or footer is False (0), it won't.

Remarks

Use the CreateGroupLevel function when designing a wizard that creates a report with groups or totals. CreateGroupLevel will group or sort data on the specified field or expression and create a header and/or footer for the group level.

The CreateGroupLevel function is available only in report Design view.

Microsoft Access uses an array, the GroupLevel property array, to keep track of the group levels created for a report. CreateGroupLevel adds a new group level to the array, based on the expression argument. CreateGroupLevel then returns an index value that represents the new group level's position in the array. The first field or expression you sort or group on is level 0, the second is level 1, and so on. You can have up to ten group levels in a report (0 to 9).

When you specify that either header or footer argument, or both, is True, the GroupHeader and GroupFooter properties in a report are set to Yes, and a header and/or footer is created for the group level.

Once a header or footer is created, you can set other GroupLevel properties: GroupOn, GroupInterval, and KeepTogether. You can set these properties in Visual Basic, or you can set them in the report's Sorting and Grouping Box.

Tip   If your wizard creates group levels in a new or existing report, it must open the report in Design view.


CreateGroupLevel Function Example

The following example function creates a group level on an OrderDate field on a report called OrderReport. The report on which the group level is to be created must be open in Design view. Since the header and footer arguments are set to True, the function creates both the header and footer for the group level. The header and footer are then sized.

Sub CreateGL()

Dim varGroupLevel As Variant

' Create new group level on OrderDate field.

varGroupLevel = CreateGroupLevel("OrderReport", "OrderDate", _

True, True)
' Set height of header/footer sections.
Reports!OrderReport.Section(acGroupLevel1Header).Height = 400
Reports!OrderReport.Section(acGroupLevel1Footer).Height = 400
End Sub


DeleteControl, DeleteReportControl Statements

You can use the DeleteControl and DeleteReportControl statements to delete a specified control from a form or report.

For example, suppose you have a procedure that must be run the first time each user logs into your database. You can set the OnClick property of a button on the form to this procedure. Once the user has logged on and run the procedure, you can use the DeleteControl statement to dynamically remove the command button from the form.

Syntax

DeleteControl formname, controlname

DeleteReportControl reportname, controlname

The DeleteControl and DeleteReportControl statements have the following arguments.

Argument	Description

formname, reportname	A string expression identifying the name of the form or report containing the control you want to delete.

controlname	A string expression identifying the name of the control you want to delete.

Remarks

The DeleteControl and DeleteReportControl statements are available only in form Design view or report Design view, respectively.

Tip   If you are building a wizard that deletes a control from a form or report, your wizard must open the form or report in Design view before it can delete the control.


DeleteControl, DeleteReportControl Statements Example

The following example creates a form with a command button and displays a message asking if the user wants to delete the command button. If the user chooses Yes, the command button is deleted.

Sub DeleteCommandButton()

Dim frm As Form, ctlNew As Control

Dim strMsg as String, intResponse as Integer, intDialog as Integer

' Create new form and get pointer to it.

Set frm = CreateForm

' Create new command button.
Set ctlNew = CreateControl(frm.Name, acCommandButton)

' Restore form.

DoCmd.Restore

' Set caption.

ctlNew.Caption = "New Command Button"

' Size control.

ctlNew.SizeToFit

' Prompt user to delete control.

strMsg = "About to delete " & ctlNew.Name &". Continue?"

intDialog = vbYesNo + vbCritical + vbDefButton2

intResponse = MsgBox(strMsg, intDialog)

If intResponse = vbYes Then

' Delete control.

DeleteControl frm.Name, ctlNew.Name

End If

End Sub


InsertText Method

You can use the InsertText method from Visual Basic code to add text to another module.

For example, suppose you are building a wizard that creates a new form and adds code to that form's module. You can use the InsertText method to add the specified text to the module when the wizard is run.

Setting

The InsertText method uses two syntax forms.

Syntax 1

object.Module.InsertText text

You can use this syntax form to insert text into a form module or a report module.  This syntax form uses the following arguments.

Argument	Description

object	A Form or Report object containing the module to which you want to add text.

Module	The property that specifies a form or report module.

text	A string expression that specifies the text to insert.

Syntax 2

application.InsertText text, modulename

You can use this syntax form to insert text into a standard module.  This syntax form uses the following arguments.

Argument	Description

application	The Application object.

text	The text to insert.

modulename	The name of the standard module into which text is to be inserted.

Remarks

Use the InsertText method in a custom wizard to add code to a module.

If you are adding text to a form or report module, the InsertText method is available only in form Design view or report Design view. If you try to add text to the module of a form or report that is open in any view but Design view, Microsoft Access generates a run-time error.

If a procedure in the module to which you are adding text is suspended, Microsoft Access generates a run-time error.


InsertText Method Example

The following example inserts code in the form module associated with a form called Orders. The code sounds a beep when the form is opened.

Sub AddSub()

Dim strFormOpenCode As String

strFormOpenCode = "Sub Form_Open(Cancel As Integer)" & vbCrLf _

& "Beep" & vbCrLf & "End Sub"

Forms!Orders.Module.InsertText strFormOpenCode

End Sub

The next example inserts code into a standard module called PublicFunctions.

Sub AddDeclaration()

Dim strText As String

strText = "Public varName"

Application.InsertText strText, "PublicFunctions"

End Sub


SysCmd Function

You can use SysCmd to perform one of the following functions:

Display a progress meter or optional specified text in the status bar.

Return information about Microsoft Access and its associated files.

Return the state of a specified database object to indicate whether the object is open, is a new object, or has been changed but not saved.

For example, if you are building a custom wizard that creates a new form, you can use the SysCmd function to display a progress meter indicating the progress of your wizard as it constructs the form.

Syntax

ReturnValue = SysCmd(action[, text][, value])

ObjectState = SysCmd(action[, objecttype][, objectname])

The SysCmd function syntax has the following arguments.

Argument	Description

action	One of the following intrinsic constants identifying the type of action to take.

This set of constants applies to a progress meter. SysCmd returns a Null if these actions are successful. Otherwise, Microsoft Access generates a run-time error.

acSysCmdInitMeter	Initializes the progress meter. You must specify the text and value arguments when you use this action.
acSysCmdUpdateMeter	Updates the progress meter with the specified value. You must specify the text argument when you use this action.
acSysCmdRemoveMeter	Removes the progress meter.
acSysCmdSetStatus	Sets the status bar text to text.
acSysCmdClearStatus	Resets the status bar text.
This set of constants provides information about Microsoft Access.

acSysCmdRuntime	Returns True if a run-time version of Microsoft Access is running.
acSysCmdAccessVer	Returns the version number of Microsoft Access.
acSysCmdIniFile	Returns the name of the .ini file associated with Microsoft Access.
acSysCmdAccessDir	Returns the name of the directory where Msaccess.exe is located.
acSysCmdProfile	Returns the /profile setting specified by the user when starting Microsoft Access from the command line.
acSysCmdGetWorkgroupFile	Returns the path to the workgroup file (System.mdw).
This constant provides information on the state of a database object:

acSysCmdGetObjectState	Returns the state of the specified database object. You must specify the objecttype and objectname parts when you use this action value.
text	A string expression identifying the text to be displayed left-aligned in the status bar. Required when action is acSysCmdInitMeter, acSysCmdUpdateMeter, or acSysCmdSetStatus; not valid for other action values.

value	A numeric expression that controls the display of the progress meter. Required when action is acSysCmdInitMeter; not valid for other action values.

objecttype	One of the following intrinsic constants:

acTable
acQuery
acForm
acReport
acMacro
acModule

Required when action is acSysCmdGetObjectState; not valid for other action values.

objectname	A string expression that is the valid name of a database object of the type specified by the objecttype argument. Required when action is acSysCmdGetObjectState; not valid for other action values.

Remarks

By calling the SysCmd function with the various progress meter actions, you can display a progress meter in the status bar for an operation that has a known duration or number of steps, and update it to indicate the progress of the operation.

To display a progress meter in the status bar, you must first call the SysCmd function with the acSysCmdInitMeter action and the text and value arguments. When the action argument is acSysCmdInitMeter, value is the maximum value of the meter, or 100 percent.

To update the meter to show the progress of the operation, call SysCmd with the acSysCmdUpdateMeter action and the value argument. When action is acSysCmdUpdateMeter, SysCmd uses the value argument to calculate the percentage displayed by the meter. For example, if you set the maximum value to 200 and then update the meter with a value of 100, the progress meter will be half-filled.

You can also change the text that is displayed in the status bar by calling SysCmd with the acSysCmdSetStatus action and the text argument. For example, during a sort you might change the text to "Sorting...". When the sort is complete, you would reset the status bar by removing the text. The text argument can contain approximately 80 characters. Because the status bar text is displayed using a proportional font, the actual number of characters you can display is determined by the total width of all the characters specified by text.

As you increase the width of the status bar text, you decrease the length of the meter. If the text is longer than the status bar and action is acSysCmdInitMeter, SysCmd ignores the text and doesn't display anything in the status bar. If the text is longer than the status bar and action is acSysCmdSetStatus, SysCmd truncates the text to fit the status bar.

You can't set the status bar text to a zero-length string (" "). If you want to remove the existing text from the status bar, set the text argument to a single space. The following examples illustrate ways to remove the text from the status bar:

varReturn = SysCmd(acSysCmdInitMeter, " ", 100)

varReturn = SysCmd(acSysCmdSetStatus, " ")

If the progress meter is already displayed when you set the text by calling SysCmd with the acSysCmdSetStatus action, the SysCmd function automatically removes the meter.

Call SysCmd with other actions to determine system information about Microsoft Access, including which version number of Microsoft Access is running, whether it is a run-time version, the location of the Microsoft Access executable file, the setting for the /Profile argument specified in the command line, and the name of an .ini file associated with Microsoft Access.

Note   Both general and customized settings for Microsoft Access are now stored in the Windows Registry, so you most likely won't need an .ini file with your Microsoft Access application. The acSysCmdIniFile action exists for compatibility with earlier versions of Microsoft Access.

Call SysCmd with the acSysCmdGetObjectState action and the objecttype and objectname arguments to return the state of a specified database object. An object can be in one of four possible states: not open or nonexistent, open, new, or changed but not saved.

For example, if you are designing a wizard that inserts a new field in a table, you need to determine whether the structure of the table has been changed but not yet saved, so that you can save it before modifying its structure. You can check the value returned by SysCmd to determine the state of the table.

The SysCmd function with the acSysCmdGetObjectState action can return any combination of the following constants.

Constant	State of database object

acObjStateOpen	Open

acObjStateNew	New

acObjStateDirty	Changed but not saved

Note   If the object referred to by objectname is either not open or does not exist, SysCmd returns a value of zero.


SysCmd Function Examples

The following example creates a snapshot-type Recordset object, reads each record, and displays a progress meter showing the current relative position in the snapshot.

Function ReadRecords (strTableName As String) As Integer

Const conBadArgs = -1

Dim dbs As Database, rst As RecordSet
Dim lngCount As Long, strMsg As String

Dim varReturn As Variant, lngX As Long

ReadRecords = 0

If strTableName <> "" Then
DoCmd.Hourglass True
Set dbs = CurrentDb
On Error Resume Next
Set rst = dbs.OpenRecordSet(strTableName)

' Get record count.
rst.MoveLast
rst.MoveFirst
If Err Then
ReadRecords = conBadArgs
End If

lngCount = rst.RecordCount
On Error GoTo 0

If lngCount Then
strMsg = "Reading " & UCase$(strTableName) & "..."
ReturnValue = SysCmd(acSysCmdInitMeter , strMsg, lngCount)

' Display message in status bar.
For lngX = 1 To lngCount
varReturn = SysCmd(acSysCmdUpdateMeter, lngX)

' Update meter.
.	' Do something with record.

.

.

rst.MoveNext	' Go to next record.
Next lngX

GoSub CloseObjects
ReadRecords = lngCount	' Return number of records.
Exit Function
End If
End If

' Not found or contains no records.

strMsg = "Table '" & strTableName & "'not found or contains no records.'"
MsgBox strMsg, vbInformation, "ReadRecords"
GoSub CloseObjects
Exit Function

CloseObjects:
On Error Resume Next
rst.Close
dbs.Close
On Error GoTo 0
DoCmd.Hourglass False
Return

End Function

The next example illustrates how you can use the SysCmd function with the acSysCmdGetObjectState action to determine the state of the active database object.

Dim intObjType As Integer, strObjName As String, intObjState As Integer

intObjType = Application.CurrentObjectType
strObjName = Application.CurrentObjectName

intObjState = SysCmd(acSysCmdGetObjectState, intObjType, strObjName)

If intObjState <> 0 Then
.

.

.

End If