782
Microsoft Access Language Reference Página 1 de 782 file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01 Microsoft Access Language Reference Default location: \Program Files\Microsoft Office\Office AccessError Method Applies To Application object. Description

Microsoft Access Language

Embed Size (px)

Citation preview

Page 1: Microsoft Access Language

Microsoft Access Language Reference Página 1 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Microsoft Access Language ReferenceDefault location: \Program Files\Microsoft Office\Office

AccessError Method

Applies To

Application object.

Description

Page 2: Microsoft Access Language

Microsoft Access Language Reference Página 2 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the AccessError method to return the descriptive string associated with a Microsoft Access error or a DAO error.

Syntax

[application.]AccessError(errornumber)

The AccessError method has the following arguments.

Remarks

You can use the AccessError method to return the descriptive string associated with a Microsoft Access error or a DAO error when the error hasn't actually occurred.

You can use the Visual Basic Raise method to raise a Visual Basic error. Once you've raised the error, you can determine its associated descriptive string by reading the Description property of the Err object.

You can't use the Raise method to raise a Microsoft Access error or a DAO error. However, you can use the AccessError method to return the descriptive string associated with these errors, without having to generate the error.

You can use the AccessError method to return a descriptive string from within a form's Error event.

If the Microsoft Access error has occurred, you can return the descriptive string by using either the AccessError method or the Description property of the Visual Basic Err object.

See Also

Err object, Error object.

Example

The following function returns an error string for any valid error number:

Function ErrorString(lngError As Long) As String Const conAppError = "Application-defined or object-defined error"

On Error Resume Next Err.Raise lngError If Err.Description = conAppError Then

Argument Description

application Optional. The Application object.

errornumber The number of the error for which you wish to return a descriptive string.

Page 3: Microsoft Access Language

Microsoft Access Language Reference Página 3 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ErrorString = AccessError(lngError) ElseIf Err.Description = "" Then MsgBox "No error string associated with this number." Else ErrorString = Err.Description End IfEnd Function

Action Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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 Description

acOLECreateEmbed 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 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 by using this setting, the control displays a

Page 4: Microsoft Access Language

Microsoft Access Language Reference Página 4 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 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 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 the acOLEPaste setting is equivalent to clicking Paste on the Edit menu.

acOLEUpdate Retrieves the current data from the application that supplied the object and displays that data as a metafile graphic in the control.

acOLEActivate 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.

Page 5: Microsoft Access Language

Microsoft Access Language Reference Página 5 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

acOLEClose 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 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 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) by using this dialog box.

acOLEPasteSpecialDlg 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) by using this dialog box.

Page 6: Microsoft Access Language

Microsoft Access Language Reference Página 6 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the Action property only by using Visual Basic. The Action property setting is 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's Enabled property is set to No or its Locked property is set to Yes, you can't use some Action property settings. The following table indicates which settings are allowed or not allowed under these conditions.

acOLEFetchVerbs Updates the list of verbs an OLE object supports. To display the list of verbs, use the ObjectVerbs and ObjectVerbsCount properties.

Setting Enabled = No

Locked = Yes

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

Page 7: Microsoft Access Language

Microsoft Access Language Reference Página 7 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

AutoActivate property, Class property, Enabled, Locked properties, ObjectVerbs property, ObjectVerbsCount property, OLEType property, OLETypeAllowed property, SourceDoc property, SourceItem property, UpdateOptions property, Verb property.

Example

The following example creates a linked OLE object using an unbound object frame named OLE1 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 create link to. OLE1.Action = acOLECreateLink ' Create linked object. OLE1.SizeMode = acOLESizeZoom ' Adjust control size.End Sub

Activate, Deactivate Events

Applies To

Form, Report.

Description

l The Activate event occurs when a form or report receives the focus and becomes the active window.

l The Deactivate event occurs 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

To run a macro or event procedure when these events occur, set the OnActivate or OnDeactivate property to the name of the macro or to [Event Procedure].

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

acOLEFetchVerbs Not allowed Allowed

Page 8: Microsoft Access Language

Microsoft Access Language Reference Página 8 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

See Also

Current event, Event properties, GotFocus, LostFocus events, GoToRecord action, Load, Unload events, Open, Close events, Resize event, SetFocus method.

Activate, Deactivate Events — Event Procedures

Description

To create an event procedure that runs 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 on a form, also make sure to hide the toolbar in response to the Unload event for the form, because the Deactivate event doesn't occur when a form is unloaded. Don't use the GotFocus or LostFocus event to display or hide a toolbar on a form, because these events aren't triggered on forms that contain enabled controls.

You can't cancel the Activate or Deactivate event.

See Also

Page 9: Microsoft Access Language

Microsoft Access Language Reference Página 9 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Activate, Deactivate events — macros.

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.

To try the example, add the following event procedure to a form that has a custom toolbar called CustomToolbar.

Private Sub Form_Activate() ' Display custom toolbar. DoCmd.ShowToolbar "CustomToolbar", acToolbarYesEnd Sub

Private Sub Form_Deactivate() ' Hide custom toolbar. DoCmd.ShowToolbar "CustomToolbar", acToolbarNoEnd Sub

Activate, Deactivate Events — Macros

Description

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 on a form, also make sure to hide the toolbar in response to the Unload event for the form, because the Deactivate event doesn't occur when a form is unloaded. Don't use the GotFocus or LostFocus event to display or hide a custom toolbar on a form, because these events aren't triggered on forms that contain enabled controls.

You can't use the CancelEvent action in an Activate or Deactivate macro.

See Also

Activate, Deactivate events — event procedures.

ActiveControl Property

Applies To

Page 10: Microsoft Access Language

Microsoft Access Language Reference Página 10 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Screen object.

Description

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 a reference to the Control object that has the focus at run time.

This property is available by using a macro or 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 run time 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 ctlCurrentControl As ControlDim strControlName As StringSet ctlCurrentControl = Screen.ActiveControlstrControlName = ctlCurrentControl.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.

See Also

ActiveDatasheet property, ActiveForm property, ActiveReport property, Me property.

Example

The following example assigns the active control to the ctlCurrentControl variable and then takes different actions depending on the value of the control's Name property.

Dim ctlCurrentControl As Control

Set ctlCurrentControl = Screen.ActiveControlIf ctlCurrentControl.Name = "txtCustomerID" Then . ' Do this. . .ElseIf ctlCurrentControl.Name = "btnCustomerDetails" Then . ' Do this. . .End If

ActiveDatasheet Property

Applies To

Page 11: Microsoft Access Language

Microsoft Access Language Reference Página 11 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Screen object.

Description

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 by using a macro or Visual Basic and is read-only in all views.

Remarks

You can use this 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

See Also

ActiveControl property, ActiveForm property, ActiveReport property, SelHeight, SelWidth properties, SelTop, SelLeft properties.

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 objDatasheet As Object Dim lngFirstRow As Long, lngFirstColumn As Long Const conNoActiveDatasheet = 2484 On Error GoTo GetSelection_Err Set objDatasheet = Screen.ActiveDatasheet lngFirstRow = objDatasheet.SelTop lngFirstColumn = objDatasheet.SelLeft MsgBox "The first item in this selection is located at " _ & "Row " & lngFirstRow & ", Column " & lngFirstColumnGetSelection_Bye: Exit SubGetSelection_Err: If Err = conNoActiveDatasheet Then Resume GetSelection_Bye End IfEnd Sub

ActiveForm Property

Applies To

Page 12: Microsoft Access Language

Microsoft Access Language Reference Página 12 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Screen object.

Description

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 a reference to the Form object that has the focus at run time.

This property is available by using a macro or 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 frmCurrentForm As FormSet frmCurrentForm = Screen.ActiveFormMsgBox "Current form is " & frmCurrentForm.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.

See Also

ActiveControl property, ActiveDatasheet property, ActiveReport property, Me property.

ActiveReport Property

Applies To

Screen object.

Description

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 a reference to the Report object that has the focus at run time.

This property is available only by using a macro or Visual Basic and is read-only in all views.

Remarks

Page 13: Microsoft Access Language

Microsoft Access Language Reference Página 13 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 rptCurrentReport As ReportSet rptCurrentReport = Screen.ActiveReportMsgBox "Current report is " & rptCurrentReport.Name

If no report has the focus when you use the ActiveReport property, an error occurs.

See Also

ActiveControl property, ActiveDatasheet property, ActiveForm property, Me property.

Add Method (Pages Collection)

Applies To

Pages collection.

Description

The Add method adds a new Page object to the Pages collection of a tab control.

Syntax

object.Add [before]

The Add method has the following arguments.

Remarks

Argument Description

object The Pages collection of a tab control.

before An integer that specifies the index of the Page object before which the new Page object should be added. The index of the Page object corresponds to the value of the PageIndex property for that Page object. If you omit this argument, the new Page object is added to the end of the collection.

Page 14: Microsoft Access Language

Microsoft Access Language Reference Página 14 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The first Page object in the Pages collection corresponds to the leftmost page in the tab control and has an index of 0. The second Page object is immediately to the right of the first page and has an index of 1, and so on for all the Page objects in the tab control.

If you specify 0 for the before argument, the new Page object is added before the first Page object in the Pages collection. The new Page object then becomes the first Page object in the collection, with an index of 0.

You can add a Page object to the Pages collection of a tab control only when the form is in Design view.

See Also

Remove method (Pages collection).

Example

The following example adds a page to a tab control on a form that's in Design view. To try this example, create a new form named Form1 with a tab control named TabCtl0. Paste the following code into a standard module and run it:

Function AddPage() As Boolean Dim frm As Form Dim tbc As TabControl, pge As Page

On Error GoTo Error_AddPage Set frm = Forms!Form1 Set tbc = frm!TabCtl0 tbc.Pages.Add AddPage = True

Exit_AddPage: Exit Function

Error_AddPage: MsgBox Err & ": " & Err.Description AddPage = False Resume Exit_AddPageEnd Function

The next example removes pages from the tab control:

Function RemovePage() As Boolean Dim frm As Form Dim tbc As TabControl, pge As Page

On Error GoTo Error_RemovePage Set frm = Forms!Form1 Set tbc = frm!TabCtl0 tbc.Pages.Remove RemovePage = True

Exit_RemovePage: Exit Function

Error_RemovePage: MsgBox Err & ": " & Err.Description RemovePage = False Resume Exit_RemovePageEnd Function

Page 15: Microsoft Access Language

Microsoft Access Language Reference Página 15 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

AddColon, AutoLabel Properties

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Subform/Subreport control, Text Box control, Toggle Button control.

Description

l The AddColon property specifies whether a colon follows the text in labels for new controls.l The AutoLabel property specifies whether labels are automatically created and attached to

new controls.

Setting

The AddColon property uses the following settings.

The AutoLabel property uses the following settings.

You can set these properties only by using a control's default control style or the DefaultControl method in Visual Basic.

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

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.

Setting Description

Yes A label is attached to new controls.

No A label isn't attached to new controls.

Page 16: Microsoft Access Language

Microsoft Access Language Reference Página 16 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

using a Microsoft Access wizard, see Specify a new template for forms and reports.

See Also

LabelAlign, TextAlign properties.

AddFromFile Method (Module Object)

Applies To

Module object.

Description

The AddFromFile method adds the contents of a text file to a Module object. The Module object may represent a standard module or a class module.

Syntax

object.AddFromFile filename

The AddFromFile method has the following arguments.

Remarks

The AddFromFile method places the contents of the specified text file immediately after the Declarations section and before the first procedure in the module if it contains other procedures.

The AddFromFile method enables you to import code or comments stored in a text file.

In order to add the contents of a file to a form or report module, the form or report must be open in form Design view or report Design view. In order to add the contents of a file to a standard module or class module, the module must be open.

See Also

AddFromString method.

Argument Description

object A Module object.

filename The name and full path of a text (.txt) file or another file that stores text in an ANSI format.

Page 17: Microsoft Access Language

Microsoft Access Language Reference Página 17 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

The following function uses the AddFromString and AddFromFile methods to add a string and the contents of a text file to a standard module:

Function AddTextToModule(strModuleName As String, strFileName As String, _ strText As String) As Boolean Dim mdl As Module

On Error GoTo Error_AddTextToModule DoCmd.OpenModule strModuleName Set mdl = Modules(strModuleName) mdl.AddFromFile strFileName mdl.AddFromString strText AddTextToModule = True

Exit_AddTextToModule: Exit Function

Error_AddTextToModule: MsgBox Err & ": " & Err.Description AddTextToModule = False Resume Exit_AddTextToModuleEnd Function

You could call the preceding function from a procedure such as the following. Create a text file called Functions.txt, add some Visual Basic procedures, and save it in the My Documents directory. Then paste both the preceding procedure and the following procedure into a new standard module in the Northwind sample database. Run the following procedure:

Sub AddFunctionsFromText() Dim strModuleName As String, strFileName As String Dim strText As String

strModuleName = "Utility Functions" strFileName = "C:\My Documents\Functions.txt" strText = "Public intX As Integer" & vbCrLf _ & "Const conPathName As String = " _ & """C:\Program Files\Microsoft Office\Office\Samples\""" If AddTextToModule(strModuleName, strFileName, strText) = True Then Debug.Print "String and file contents added successfully." Else Debug.Print "String and file contents not added successfully." End IfEnd Sub

The next example creates a new form and adds a string and the contents of the Functions.txt file to its module. Run the following procedure from a standard module:

Sub AddTextToFormModule() Dim frm As Form, mdl As Module

Set frm = CreateForm Set mdl = frm.Module mdl.AddFromString "Public intY As Integer" mdl.AddFromFile "C:\My Documents\Functions.txt"End Sub

AddFromFile Method (References Collection)

Applies To

Page 18: Microsoft Access Language

Microsoft Access Language Reference Página 18 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Reference object.

Description

The AddFromFile method creates a reference to a type library in a specified file.

Syntax

Set object = References.AddFromFile(filename)

The AddFromFile method has the following arguments.

Remarks

The following table lists types of files that commonly contain type libraries.

See Also

AddFromGUID method, InsertLines method.

Example

Argument Description

object A Reference object.

filename A string expression that evaluates to the full path and file name of the file containing the type library to which you wish to set a reference.

File extension Type of file

.olb, .tlb Type library file

.mdb, .mda, .mde Database

.exe, .dll Executable file

.ocx ActiveX control

Page 19: Microsoft Access Language

Microsoft Access Language Reference Página 19 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The following example creates a reference to a specified type library:

Function ReferenceFromFile(strFileName As String) As Boolean Dim ref As Reference

On Error GoTo Error_ReferenceFromFile ' Create new reference. Set ref = References.AddFromFile(strFileName) ReferenceFromFile = True

Exit_ReferenceFromFile: Exit Function

Error_ReferenceFromFile: MsgBox Err & ": " & Err.Description ReferenceFromFile = False Resume Exit_ReferenceFromFileEnd Function

You could call this function by using a procedure such as the following, which creates a reference to the calendar control:

Sub CreateCalendarReference() If ReferenceFromFile("C:\Windows\System\Mscal.ocx") = True Then MsgBox "Reference to calendar control created successfully." Else MsgBox "Reference to calendar control not created successfully." End IfEnd Sub

AddFromGUID Method

Applies To

Reference object.

Description

The AddFromGUID method creates a Reference object based on the GUID that identifies a type library.

Syntax

object.AddFromGUID(guid)

The AddFromGUID method has the following arguments.

Argument Description

object A Reference object.

Page 20: Microsoft Access Language

Microsoft Access Language Reference Página 20 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The GUID property returns the GUID for a specified Reference object. If you've stored the value of the GUID property, you can use it to re-create a reference that's been broken.

See Also

AddFromFile method (References collection), GUID property, Major property, Minor property.

AddFromString Method

Applies To

Module object.

Description

The AddFromString method adds a string to a Module object. The Module object may represent a standard module or a class module.

Syntax

object.AddFromString stringexpression

The AddFromString method has the following arguments.

Remarks

The AddFromString method places the contents of a string after the Declarations section and before the first existing procedure in the module if the module contains other procedures.

In order to add a string to a form or report module, the form or report must be open in form Design view or report Design view. In order to add a string to a standard module or class module, the module must be open.

guid A GUID that identifies a type library.

Argument Description

object A Module object.

stringexpression A string expression.

Page 21: Microsoft Access Language

Microsoft Access Language Reference Página 21 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

AddFromFile method (Module object).

Example

See the AddFromFile method (Module object) example.

AddMenu Action

Description

You can use the AddMenu action to create:

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

l 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.

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

l A global shortcut menu. The global shortcut menu replaces the built-in shortcut menu for fields in table and query datasheets, forms in Form view, Datasheet view, and Print Preview, and reports in Print Preview, except where you've added a custom shortcut menu for a form, form control, or report.

Note While you can still create all these types of custom menus by using macros containing AddMenu actions in Microsoft Access 97 (and any existing custom menus you've created by using macros will still work), it's recommended that you create them by using the Customize dialog box, available by pointing to Toolbars on the View menu and clicking Customize. While the Customize dialog box is displayed, you can easily create a new menu or customize a built-in menu.

Setting

The AddMenu action has 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. Enter the menu name in the Menu Name box in the Action Arguments section of the Macro window. 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.

Page 22: Microsoft Access Language

Microsoft Access Language Reference Página 22 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

To create a custom menu bar, a custom shortcut menu, a global menu bar, or a global shortcut menu by using macros, 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 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.

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

To create an access key so that you can use the keyboard to choose the menu, type an ampersand (&) before the letter you want to be the access key. This letter will be underlined in the menu name on the menu bar.

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.

Page 23: Microsoft Access Language

Microsoft Access Language Reference Página 23 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 RunCommand 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.

When you specify a menu bar macro for a form or report or for the database, Microsoft Access runs this menu bar macro whenever the form, report, or database is opened. If you make changes to the menu bar macro or the macro groups that define the commands on the drop-down menus while the form, report, or database is open, you must close the form, report, or database and reopen it to see the changes in the custom menu bar and its menus.

When you are creating the macro groups that contain the commands for a custom menu, the following information applies:

l In the macro group, the name in the Macro Name column for each macro will be the command name. The text in the Comment column in that row will appear in the status bar when you choose the command.

l To create a line between two menu commands, type a hyphen (-) in the Macro Name column between the appropriate menu commands.

l To create an access key so that you can use the keyboard to choose the command, type an ampersand (&) before the letter you want to be the access key in the command name. This letter will be underlined on the menu.

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 Macro Name and Comment columns of such an AddMenu action (which normally specify the command name and status bar text for a command on the custom menu) 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.

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

Page 24: Microsoft Access Language

Microsoft Access Language Reference Página 24 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Application object, Event properties, MenuBar property, ShortcutMenuBar property, StartupMenuBar property, StartupShortcutMenuBar property.

AddToFavorites Method

Applies To

Application object, Command Button control.

Description

The AddToFavorites method adds a hyperlink address to the Favorites folder.

Syntax

object.hyperlink.AddToFavorites

The AddToFavorites method has the following arguments.

Remarks

When applied to the Application object, the AddToFavorites method adds the name of the current database to the Favorites folder. For example, if you're working in the Northwind sample database, applying the AddToFavorites method to the Application object adds the hyperlink address of the Northwind database to the Favorites folder.

When applied to a Control object, the AddToFavorites method adds the hyperlink address contained in a control to the Favorites folder. The Favorites folder is installed in the Windows folder by default.

Argument Description

object The Application object, or a Control object that contains a hyperlink. Label, command button, and image controls can contain hyperlinks.

hyperlink The hyperlink of the Control object.

Page 25: Microsoft Access Language

Microsoft Access Language Reference Página 25 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The AddToFavorites method has the same effect as clicking AddToFavorites on the Favorites menu on the Web toolbar when the document whose address you wish to add is open.

See Also

Follow method, FollowHyperlink method.

Example

The following example sets the HyperlinkAddress property of a command button. When the user clicks the command button, the address is added to the Favorites folder by using the AddToFavorites method.

To try this example, create a new form and add a command button named Command0. Paste the following code into the form's module. Switch to Form view and click the command button.

Private Sub Form_Load() Me!Command0.HyperlinkAddress = "http://www.microsoft.com/"End Sub

Private Sub Command0_Click() Me!Command0.Hyperlink.AddToFavoritesEnd Sub

AfterDelConfirm Event

See Delete, BeforeDelConfirm, AfterDelConfirm Events.

AfterInsert Event

See BeforeInsert, AfterInsert Events.

AfterUpdate Event

See BeforeUpdate, AfterUpdate Events.

Alias Property

Applies To

Action query, Crosstab query, Parameter query, Query field, Select query, SQL-Specific query.

Page 26: Microsoft Access Language

Microsoft Access Language Reference Página 26 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the Alias property to specify a custom name for a source 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 they are used as the source of data in a query.

Setting

You can use a string expression to set the Alias property to any name not currently being used in the database. You set this property in query Design view by right-clicking the field list in the query design grid and clicking 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 a 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 property to the object name plus an underscore and a 1 ("_1").

Creating an alias doesn't change the name of the table or query — 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.

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 StringstrGetSQL = "SELECT 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

The next 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 enter the following SQL statement in SQL view of the Query window.

SELECT Employees.FirstName, Employees.LastName, Employees.Title, Managers.FirstName, Managers.LastNameFROM Employees INNER JOIN Employees AS ManagersON Employees.ReportsTo = Managers.EmployeeID;

AllowAdditions Property

Page 27: Microsoft Access Language

Microsoft Access Language Reference Página 27 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Form.

Description

You can use the AllowAdditions property to specify whether a user can add a record when using a form.

Setting

The AllowAdditions property uses the following settings.

You can set the AllowAdditions property by using the form's property sheet, a macro, or 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 the AllowAdditions property is set to No, the Data Entry command on the Records menu isn't available.

Note When the Data Mode argument of the OpenForm action is used, Microsoft Access will override a number of form property settings. If the Data Mode argument of the OpenForm action is set to Edit, Microsoft Access will open the form with the following property settings:

l AllowEdits — Yesl AllowDeletions — Yesl AllowAdditions — Yesl DataEntry — No

Setting Description Visual Basic

Yes (Default) The user can add new records.

True –1)

No The user can't add new records.

False (0)

Page 28: Microsoft Access Language

Microsoft Access Language Reference Página 28 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To prevent the OpenForm action from overriding any of these existing property settings, omit the Data Mode argument setting so that Microsoft Access will use the property settings defined by the form.

See Also

AllowDeletions property, AllowEdits property, DataEntry property, OpenForm action, OpenForm method, RecordsetType property.

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, the intCanEdit variable is toggled to allow editing of the underlying data.

Sub ToggleControl(frm As Form) Dim ctl As Control Dim intI As Integer, intCanEdit As Integer Const conTransparent = 0 Const conWhite = 16777215 For Each ctl in frm.Controls With ctl Select Case .ControlType Case acLabel If .SpecialEffect = acEffectShadow Then .SpecialEffect = acEffectNormal .BorderStyle = conTransparent intCanEdit = True Else .SpecialEffect = acEffectShadow intCanEdit = False End If Case acTextBox If .SpecialEffect = acEffectNormal Then .SpecialEffect = acEffectSunken .BackColor = conWhite Else .SpecialEffect = acEffectNormal .BackColor = frm.Detail.BackColor End If End Select End With Next ctl If intCanEdit = False Then With frm .AllowAdditions = False .AllowDeletions = False .AllowEdits = False End With Else With frm .AllowAdditions = True .AllowDeletions = True .AllowEdits = True End With End IfEnd Sub

AllowAutoCorrect Property

Page 29: Microsoft Access Language

Microsoft Access Language Reference Página 29 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Combo Box control, Text Box control.

Description

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.

You can set the AllowAutoCorrect property by using a control's property sheet, a macro, or Visual Basic. You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

Remarks

The AutoCorrect dialog box is available by clicking AutoCorrect on the Tools menu.

See Also

DefaultControl method.

AllowBreakIntoCode Property

Applies To

Database object.

Description

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 Description Visual Basic

Yes (Default) Entries are automatically corrected according to the settings in the AutoCorrect dialog box.

True (–1)

No Entries aren't corrected. False (0)

Page 30: Microsoft Access Language

Microsoft Access Language Reference Página 30 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The AllowBreakIntoCode property uses the following settings.

The easiest way to set this property is by 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. You can also set this property by using a macro or Visual Basic.

To set the AllowBreakIntoCode property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

You should make sure the AllowBreakIntoCode property is set to True when debugging an application.

If the AllowSpecialKeys property is set to True, you can still press CTRL+BREAK to pause execution of Visual Basic code, even if the AllowBreakIntoCode property is set to False.

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowSpecialKeys property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference").

Example

The following example shows a procedure named SetStartupProperties that passes the name of the property to be set, its data type, and its desired setting. The general purpose procedure ChangeProperty attempts to set the startup property and, if the property isn't found, uses the CreateProperty method to append it to the Properties collection of the Database object. This is necessary because these properties don't appear in the Properties collection until they've 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

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.

Page 31: Microsoft Access Language

Microsoft Access Language Reference Página 31 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ChangeProperty "AllowBreakIntoCode", dbBoolean, False ChangeProperty "AllowSpecialKeys", dbBoolean, True ChangeProperty "AllowBypassKey", dbBoolean, TrueEnd 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 ' Property not found. Set prp = dbs.CreateProperty(strPropName, _ varPropType, varPropValue) dbs.Properties.Append prp Resume Next Else ' Unknown error. ChangeProperty = False Resume Change_Bye End IfEnd Function

AllowBuiltInToolbars Property

Applies To

Database object.

Description

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 uses 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.

Page 32: Microsoft Access Language

Microsoft Access Language Reference Página 32 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The easiest way to set this property is by using the Allow Built-in Toolbars option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the AllowBuiltInToolbars property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

You can show and hide specific toolbars by using the Customize dialog box, available by pointing to Toolbars on the View menu and clicking Customize.

If you click Toolbars on the View menu when the AllowBuiltInToolbars property is set to False, Microsoft Access will show only custom toolbars in the Toolbars submenu. If you click Customize in this submenu, the Customize dialog box shows the built-in toolbars, but you can't select them or customize them.

The user can modify built-in toolbars only when the AllowToolbarChanges property is set to True and the AllowBuiltInToolbars property is set to True.

If the AllowBuiltInToolbars property is set to False, you can't use the ShowToolbar action to display a built-in toolbar.

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AllowToolbarChanges property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference"), ShowToolbar action.

Example

See the AllowBreakIntoCode property example.

AllowBypassKey Property

Applies To

Database object.

Description

You can use the AllowBypassKey property to specify whether or not the SHIFT key is enabled for bypassing the startup properties and 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

Page 33: Microsoft Access Language

Microsoft Access Language Reference Página 33 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The AllowBypassKey property uses the following settings.

You can set this property by using a macro or Visual Basic.

To set the AllowBypassKey property by using a macro or Visual Basic, you must create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

You should make sure the AllowBypassKey property is set to True when debugging an application.

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AllowSpecialKeys property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference").

Example

See the AllowBreakIntoCode property example.

AllowDeletions Property

Applies To

Form.

Description

You can use the AllowDeletions property to specify whether a user can delete a record when using a form.

Setting Description

True (–1) Enable the SHIFT key to allow the user to bypass the startup properties and the AutoExec macro.

False (0) Disable the SHIFT key to prevent the user from bypassing the startup properties and the AutoExec macro.

Page 34: Microsoft Access Language

Microsoft Access Language Reference Página 34 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The AllowDeletions property uses the following settings.

You can set the AllowDeletions property by using the form's property sheet, a macro, or 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 aren't broken.

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 the AllowDeletions property is set to No, the Delete Record command on the Edit menu isn't available.

Note When the Data Mode argument of the OpenForm action is set, Microsoft Access will override a number of form property settings. If the Data Mode argument of the OpenForm action is set to Edit, Microsoft Access will open the form with the following property settings:

l AllowEdits — Yesl AllowDeletions — Yesl AllowAdditions — Yesl DataEntry — No

To prevent the OpenForm action from overriding any of these existing property settings, omit the Data Mode argument setting so that Microsoft Access will use the property settings defined by the form.

See Also

AllowAdditions property, AllowEdits property, DataEntry property, OpenForm action, OpenForm method, RecordsetType property.

Example

See the AllowAdditions property example.

Setting Description Visual Basic

Yes (Default) The user can delete records. True (–1)

No The user can't delete records. False (0)

Page 35: Microsoft Access Language

Microsoft Access Language Reference Página 35 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

AllowEdits Property

Applies To

Form.

Description

You can use the AllowEdits property to specify whether a user can edit saved records when using a form.

Setting

The AllowEdits property uses the following settings.

You can set the AllowEdits property by using the form's property sheet, a macro, or 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 property.

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 the AllowEdits property is set to No, the Delete Record command on the Edit menu and the Data Entry command on the Records menu aren't available.

Note When the Data Mode argument of the OpenForm action is set, Microsoft Access will override a number of form property settings. If the Data Mode argument of the OpenForm action is set to Edit, Microsoft Access will open the form with the following property settings:

l AllowEdits — Yesl AllowDeletions — Yesl AllowAdditions — Yesl DataEntry — No

Setting Description Visual Basic

Yes (Default) The user can edit saved records. True (–1)

No The user can't edit saved records. False (0)

Page 36: Microsoft Access Language

Microsoft Access Language Reference Página 36 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To prevent the OpenForm action from overriding any of these existing property settings, omit the Data Mode argument setting so that Microsoft Access will use the property settings defined by the form.

See Also

AllowAdditions property, AllowDeletions property, DataEntry property, Enabled, Locked properties, OpenForm action, OpenForm method, RecordsetType property.

Example

See the AllowAdditions property examples.

AllowFilters Property

Applies To

Form.

Description

You can use the AllowFilters property to specify whether records in a form can be filtered.

Settings

The AllowFilters property uses the following settings.

You can set this property by 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 form, 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.

Setting Description Visual Basic

Yes (Default) Records can be filtered.

True (–1)

No Records can't be filtered. False (0)

Page 37: Microsoft Access Language

Microsoft Access Language Reference Página 37 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

When the AllowFilters property is set to No, all of the filter options on the Records menu, the form's shortcut menu, and the Formatting (Form/Report) toolbar are disabled. The commands and buttons include:

l The Filter, Apply Filter/Sort, and Remove Filter/Sort commands.l The Filter By Form, Apply Filter/Sort, and Remove Filter/Sort commands on the form's

shortcut menu.l The corresponding Filter By Selection, Filter By Form, and Apply Filter / Remove Filter

buttons.

Note Setting the AllowFilters property to No does not affect the Filter and FilterOn properties. You can still use these properties to set and remove filters. You can also still use the following actions or methods to apply and remove filters:

See Also

ApplyFilter event, Filter event, Filter property, FilterOn 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.AllowFiltersEnd Function

AllowFullMenus Property

Applies To

Database object.

Description

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

Actions Methods

ApplyFilter ApplyFilter

OpenForm OpenForm

ShowAllRecords ShowAllRecords

Page 38: Microsoft Access Language

Microsoft Access Language Reference Página 38 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

The easiest way to set this property is by using the Allow Full Menus option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the AllowFullMenus property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

If you set this property to False, a predefined subset of the full built-in menus is displayed in your database. This set of menus doesn't include menus and commands that enable users to change the design of database objects.

Setting this property to False also disables the toolbar buttons that correspond to the disabled menu items. However, shortcut menus aren't affected (you can still change some design features by using shortcut menu commands). If you don't want users to have access to the commands on the shortcut menus, you can set the AllowShortcutMenus property to False.

This property's setting doesn't take effect until the next time the database opens.

See Also

AllowBreakIntoCode property, AllowShortcutMenus property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference"), StartupMenuBar property, StartupShortcutMenuBar property.

Example

See the AllowBreakIntoCode property example.

AllowShortcutMenus Property

Setting Description

True (–1) Display the full built-in menus at startup.

False (0) Don't display full built-in menus at startup.

Page 39: Microsoft Access Language

Microsoft Access Language Reference Página 39 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Database object.

Description

You can use the AllowShortcutMenus property to specify whether or not your application allows Microsoft Access to display built-in shortcut menus. For example, you can use the AllowShortcutMenus property in conjunction with the AllowFullMenus property in your application to prevent users from using any built-in menu bar, toolbars, or shortcut menu commands that enable users to change the design of database objects.

Setting

The AllowShortcutMenus property uses the following settings.

The easiest way to set this property is by using the Allow Default Shortcut Menus option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the AllowShortcutMenus property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

The setting of this property doesn't affect custom shortcut menus and global shortcut menus. You can use the ShortcutMenuBar property to display custom shortcut menus for forms, form controls, and reports, and the StartupShortcutMenuBar property or the ShortcutMenuBar property of the Application object to display a global shortcut menu.

If you want to display built-in shortcut menus in your application, but don't want the user to be able to change them, set the AllowShortcutMenus property to True and set the AllowToolbarChanges property to False.

This property's setting doesn't take effect until the next time the database opens.

See Also

AllowBreakIntoCode property, AllowFullMenus property, AllowToolbarChanges property,

Setting Description

True (–1) Allow Microsoft Access built-in shortcut menus to be displayed.

False (0) Don't allow Microsoft Access built-in shortcut menus to be displayed.

Page 40: Microsoft Access Language

Microsoft Access Language Reference Página 40 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference").

AllowSpecialKeys Property

Applies To

Database object.

Description

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 by pressing F11, entering break mode within a Visual Basic module by pressing CTRL+BREAK, or displaying the Debug window by pressing CTRL+G.

Setting

The AllowSpecialKeys property uses the following settings.

The easiest way to set this property is by using the Use Access Special Keys option in the Advanced section of the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the AllowSpecialKeys property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

You should make sure the AllowSpecialKeys property is set to True when debugging an application.

The AllowSpecialKeys property affects the following key sequences.

Setting Description

True (–1) Enable the special key sequences.

False (0) Disable the special key sequences.

Page 41: Microsoft Access Language

Microsoft Access Language Reference Página 41 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

If you set the UseSpecialKeys property to False, and specify a global menu bar by using the StartupMenuBar property or the MenuBar property of the Application object, the built-in menu bar isn't accessible.

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AllowBypassKey property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference"), StartupShowDBWindow property.

Example

See the AllowBreakIntoCode property example.

AllowToolbarChanges Property

Applies To

Database object.

Description

You can use the AllowToolbarChanges property to specify whether or not your database allows users to customize toolbars, menu bars, and shortcut menus. For example, you can use the AllowToolbarChanges property to prevent users from deleting a toolbar button or an entire toolbar from your application.

Setting

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 and display the current module in the Module window.

Page 42: Microsoft Access Language

Microsoft Access Language Reference Página 42 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The AllowToolbarChanges property uses the following settings.

The easiest way to set this property is by using the Allow Toolbar/Menu Changes option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the AllowToolbarChanges property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

Setting the AllowToolbarChanges property to False prevents users from modifying any toolbars, menu bars, and shortcut menus. It disables the Customize subcommand of the Toolbars command on the View menu and the Customize command that's displayed when you right-click a toolbar or the menu bar.

If you set this property to False, the user can still move, size, and dock toolbars and the menu bar.

The user can modify built-in toolbars only when the AllowToolbarChanges property is True and the AllowBuiltInToolbars property is True.

This property's setting doesn't take effect until the next time the database opens.

See Also

AllowBreakIntoCode property, AllowBuiltInToolbars property, AllowShortcutMenus property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference"), ShowToolbar action.

AllowZeroLength Property

Applies To

Table field.

Setting Description

True (–1) Allow changes to toolbars, menu bars, and shortcut menus.

False (0) Don't allow changes to toolbars, menu bars, and shortcut menus.

Page 43: Microsoft Access Language

Microsoft Access Language Reference Página 43 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the AllowZeroLength property to specify whether a zero-length string (" ") is a valid entry in a table field.

Note The AllowZeroLength property applies only to Text, Memo, and Hyperlink table fields.

Setting

The AllowZeroLength property uses the following settings.

You can set this property by using the table's property sheet or Visual Basic.

Note To access a field's AllowZeroLength property by using Visual Basic, use the DAO AllowZeroLength property.

Remarks

If you want Microsoft Access to store a zero-length string instead of a Null value when you leave a field blank, set both the AllowZeroLength and Required properties to Yes.

The following table shows the results of combining the settings of the AllowZeroLength and Required properties.

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)

AllowZeroLength Required User's action Value stored

No No Presses ENTERPresses SPACEBAREnters a zero-length string

NullNull(not allowed)

Yes No Presses ENTERPresses SPACEBAREnters a zero-length string

NullNullZero-length string

Page 44: Microsoft Access Language

Microsoft Access Language Reference Página 44 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Tip You can use the Format property 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, a zero-length string will be a valid value for the field regardless of the setting of the Required property.

See Also

AllowZeroLength property, DefaultValue property, InputMask property, Required property, Required property ("DAO Language Reference").

AppIcon Property

Applies To

Database object.

Description

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 a picture of an automobile to represent an automotive parts application.

Setting

The AppIcon property is a string expression that's a valid bitmap or icon file name (including the path).

The easiest way to set this property is by using the Application Icon option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

No Yes Presses ENTERPresses SPACEBAREnters a zero-length string

(not allowed)(not allowed)(not allowed)

Yes Yes Presses ENTERPresses SPACEBAREnters a zero-length string

(not allowed)Zero-length stringZero-length string

Page 45: Microsoft Access Language

Microsoft Access Language Reference Página 45 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To set the AppIcon property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object. You must also use the RefreshTitleBar method to make any changes visible immediately.

Remarks

If you are distributing your application, it's recommended that the .bmp or .ico file containing the icon reside in the same directory as your Microsoft Access application.

If the AppIcon property isn't set or is invalid, the Microsoft Access icon is displayed.

This property setting takes effect immediately after it's set in code (as long as the code includes the RefreshTitleBar method) or the Startup dialog box is closed.

See Also

AppTitle property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference").

Example

The following example shows how to change the AppIcon and AppTitle properties. If the properties haven't already been set or created, you must create them and append them to the Database object by using the CreateProperty method.

Sub cmdAddProp_Click() Dim intX As Integer

intX = AddAppProperty("AppTitle", dbText, "My Custom Application") intX = AddAppProperty("AppIcon", dbText, "C:\Windows\Cars.bmp") RefreshTitleBarEnd Sub

Function AddAppProperty(strName As String, varType As Variant, _ varValue As Variant) As Integer Dim dbs As Database, prp As Property Const conPropNotFoundError = 3270

Set dbs = CurrentDb On Error GoTo AddProp_Err dbs.Properties(strName) = varValue AddAppProperty = True

AddProp_Bye: Exit Function

AddProp_Err: If Err = conPropNotFoundError Then Set prp = dbs.CreateProperty(strName, varType, varValue) dbs.Properties.Append prp Resume Else AddAppProperty = False Resume AddProp_Bye End IfEnd Function

Page 46: Microsoft Access Language

Microsoft Access Language Reference Página 46 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Application Object

Description

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 Modules collection, the References 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 Status Bar check box under Show on the View tab of the Options dialog box.

Application.SetOption "Show Status Bar", True

Microsoft Access is an ActiveX component that supports Automation, formerly called OLE Automation. You can manipulate Microsoft Access objects from another application that also supports Automation. To do this, you use the Application object.

For example, Microsoft Visual Basic is an ActiveX component. You can open a Microsoft Access database from Visual Basic and work with its objects. From Visual Basic, first create a reference to the Microsoft Access 8.0 object library. Then create a new instance of the Application class and point an object variable to it, as in the following example:

Dim appAccess As New Access.Application

From applications that don't support the New keyword, you can create a new instance of the Application class by using the CreateObject function:

Dim appAccess As ObjectSet appAccess = CreateObject("Access.Application.8")

Once you've created a new instance of the Application class, you can open a database or create a new database, by using either the OpenCurrentDatabase method or the NewCurrentDatabase method. You can then set the properties of the Application object and call its methods. When you return a reference to the DBEngine object by using the DBEngine property of the Application object, you can access all DAO objects and collections by using this reference.

You can also manipulate other Microsoft Access objects through the Application object. For example, by using the OpenForm method of the Microsoft Access DoCmd object, you can open a Microsoft Access form from Microsoft Excel:

appAccess.DoCmd.OpenForm "Orders"

For more information on creating a reference and controlling objects by using Automation, see the documentation for the application that's acting as the ActiveX component.

Properties

Page 47: Microsoft Access Language

Microsoft Access Language Reference Página 47 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Application property, CodeContextObject property, CommandBar property, CurrentObjectType, CurrentObjectName properties, DBEngine property, MenuBar property, Parent property, ShortcutMenuBar property, UserControl property, Visible property.

Methods

AccessError method, AddToFavorites method, BuildCriteria method, CloseCurrentDatabase method, DefaultWorkspaceClone method, Echo method (Application object), FollowHyperlink method, GetOption, SetOption methods, NewCurrentDatabase method, OpenCurrentDatabase method, Quit method (Application object), RefreshDatabaseWindow method, RefreshTitleBar method, Run method, RunCommand method.

See Also

CreateObject function, DBEngine object ("DAO Language Reference"), DoCmd object, Forms collection, GetObject function, Module object, Modules collection, References collection, Reports collection, Screen 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 Hidden Objects option under Show on View tab ' of Options dialog box. Application.SetOption "Show Hidden Objects", True ' Quit Microsoft Access, saving all objects. Application.Quit acSaveYesEnd Sub

The next example shows how to use Microsoft Access as an ActiveX component. From Microsoft Excel, Visual Basic, or another application that acts as an ActiveX component, create a reference to Microsoft Access by clicking References on the Tools menu in the Module window. Select the check box next to Microsoft Access 8.0 Object Library. Then enter the following code in a Visual Basic module within that application and call the GetAccessData procedure.

The example passes a database name and report name to a procedure that creates a new instance of the Application class, opens the database, and prints the specified report.

' Declare object variable in declarations section of a module. Dim appAccess As Access.Application

Sub GetAccessData() Dim strDB As String Dim strReportName As String

' Initialize string to database path. strDB = "C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb" ' Initialize string to Report name. strReportName = "Catalog" PrintAccessReport strDB, strReportNameEnd Sub

Sub PrintAccessReport(strDB As String, strReportName As String) ' Return reference to Microsoft Access Application object. Set appAccess = New Access.Application

Page 48: Microsoft Access Language

Microsoft Access Language Reference Página 48 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' Open database in Microsoft Access. appAccess.OpenCurrentDatabase strDB ' Print report. appAccess.DoCmd.OpenReport strReportName MsgBox "Click OK when " & strReportName & _ " is finished printing" appAccess.CloseCurrentDatabase Set appAccess = NothingEnd Sub

Application Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Controls collection, Form, Form section, Forms collection, Image control, Label control, Line control, List Box control, Module object, Modules collection, Option Button control, Option Group control, Page, Page Break control, Properties collection, Rectangle control, Report section, Reports collection, Screen object, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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 in all views.

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 object's properties. For example, you could refer to the menu bar for the Application object from the current form by using the following syntax:

Me.Application.MenuBar

See Also

Application object.

Example

The following example displays the DBEngine properties in a message box.

Private Sub Command1_Click() DisplayApplicationInfo MeEnd Sub

Function DisplayApplicationInfo(obj As Object) As Integer Dim objApp As Object, intI As Integer, strProps As String On Error Resume Next ' Form Application property.

Page 49: Microsoft Access Language

Microsoft Access Language Reference Página 49 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Set objApp = obj.Application MsgBox "Application Visible property = " & objApp.Visible If objApp.UserControl = True Then For intI = 0 To objApp.DBEngine.Properties.Count - 1 strProps = strProps & objApp.DBEngine.Properties(intI).Name _ & ", " Next intI End If MsgBox Left(strProps, Len(strProps) - 2) & ".", vbOK, _ "DBEngine Properties"End Function

ApplyFilter Action

Description

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 has 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 in the Filter Name box in the Action Arguments section of the Macro window.

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 a Where Condition argument 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

Page 50: Microsoft Access Language

Microsoft Access Language Reference Página 50 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

The filter and WHERE condition you apply become the setting of the form's or report's Filter property.

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 Filter 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've 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 containing the ApplyFilter action or an event procedure containing the ApplyFilter method of the DoCmd object as the OnOpen event property setting of the form. You can also apply a filter by 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 by using a macro containing the OpenTable action, followed immediately by the ApplyFilter action.

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, for example:

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.

Page 51: Microsoft Access Language

Microsoft Access Language Reference Página 51 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

ApplyFilter method, Filter property, FilterOn property, OpenForm action, OpenQuery action, OpenReport action, ShowAllRecords action, WHERE clause ("SQL Language Reference").

ApplyFilter Event

Applies To

Form.

Description

The ApplyFilter event occurs when the user does one of the following:

l Clicks Apply Filter/Sort on the Records menu in Form view, clicks Apply Filter/Sort on the Filter menu in the Filter window, or clicks the Apply Filter button on the toolbar. This applies the most recently created filter (created by using either the Filter By Form feature or the Advanced Filter/Sort window).

l On the Records menu in Form view, points to Filter and clicks Filter By Selection, or clicks the Filter By Selection button on the toolbar. This applies a filter based on the current selection in the form.

l On the Records menu in Form view, points to Filter and clicks Filter Excluding Selection. This applies a filter excluding the current selection in the form.

l Clicks Remove Filter/Sort on the Records menu in Form view, or clicks the Remove Filter button on the toolbar. This removes any filter (or sort) currently applied to the form.

l Clicks Filter By Selection, Filter Excluding Selection, or Remove Filter/Sort or enters a value or expression in the Filter For box on the shortcut menu when a bound control has the focus.

l Closes the Advanced Filter/Sort window or the Filter By Form window.l Clicks Advanced Filter/Sort on the Filter menu while the Filter By Form window is open, or

clicks Filter By Form on the Filter menu while the Advanced Filter/Sort window is open. This causes the ApplyFilter event to occur when the open filter window is closed, and then the Filter event to occur when the other filter window is opened.

Remarks

To run a macro or event procedure when this event occurs, set the OnApplyFilter property to the name of the macro or to [Event Procedure].

You can use the ApplyFilter event to:

l 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 form's Filter property value to make sure this criteria is included in the WHERE clause expression.

l 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 aren't appropriate for the records displayed by this filter.

Page 52: Microsoft Access Language

Microsoft Access Language Reference Página 52 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l 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 don't 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 doesn't occur when the user does one of the following:

l Applies or removes a filter by using the ApplyFilter, OpenForm, or ShowAllRecords actions in a macro, or their corresponding methods of the DoCmd object in Visual Basic.

l Uses the Close action or the Close method of the DoCmd object to close the Advanced Filter/Sort window or the Filter By Form window.

l Sets 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).

See Also

AllowFilters property, Event properties, Filter event, Filter property, FilterLookup property, FilterOn property, OrderBy property, OrderByOn property.

ApplyFilter Event — Event Procedures

Description

To create an event procedure that runs 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 has the following arguments.

Argument Description

Cancel The setting determines whether to apply the filter. Setting the Cancel argument to True (–1) prevents the filter from being applied. You can also use the

Page 53: Microsoft Access Language

Microsoft Access Language Reference Página 53 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 when the ApplyType argument is acCloseFilterWindow.

See Also

ApplyFilter event — macros.

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.

To try this example, add the following event procedure to an Orders form that contains

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

Page 54: Microsoft Access Language

Microsoft Access Language Reference Página 54 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

AmountDue, Tax, and TotalDue controls. Run a filter that lists 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 IfEnd Sub

ApplyFilter Event — Macros

Description

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 by 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.

See Also

ApplyFilter event — event procedures.

ApplyFilter Method

Applies To

DoCmd object.

Description

The ApplyFilter method carries out the ApplyFilter action in Visual Basic. For more information on

Page 55: Microsoft Access Language

Microsoft Access Language Reference Página 55 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

how the action and its arguments work, see the action topic.

Syntax

DoCmd.ApplyFilter [filtername][, wherecondition]

The ApplyFilter method has the following arguments.

Remarks

You must include at least one of the two ApplyFilter method arguments. If you enter a value for both arguments, the wherecondition argument 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.

See Also

ApplyFilter action, Filter property, FilterOn property, OpenForm method, OpenQuery method, OpenReport method, ShowAllRecords method.

Example

The following example uses the ApplyFilter method to display only records that contain the name King in the LastName field:

DoCmd.ApplyFilter , "LastName = 'King'"

AppTitle Property

Applies To

Database object.

Argument Description

filtername A string expression that's the valid name of a query in the current database.

wherecondition A string expression that's a valid SQL WHERE clause without the word WHERE.

Page 56: Microsoft Access Language

Microsoft Access Language Reference Página 56 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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.

The easiest way to set this property is by using the Application Title option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the AppTitle property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object. You must also use the RefreshTitleBar method to make any changes visible immediately.

Remarks

If this property isn't set, the string "Microsoft Access" appears in the title bar.

This property's setting takes effect immediately after setting the property in code (as long as the code includes the RefreshTitleBar method) or closing the Startup dialog box.

See Also

AppIcon property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference").

Example

See the AppIcon property example.

Assistant Property

Applies To

Application object.

Description

You can use the Assistant property to return a reference to the Assistant object.

Setting

[application.]Assistant[.method or property]

Page 57: Microsoft Access Language

Microsoft Access Language Reference Página 57 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The Assistant property uses the following settings.

The Assistant property is available only by using Visual Basic.

Remarks

Once you establish a reference to the Assistant object, you can access all the properties and methods of the object. You can set a reference to the Assistant object by clicking References on the Tools menu while in module Design view. Then set a reference to the Microsoft Office 8.0 Object Library in the References dialog box by selecting the appropriate check box. Microsoft Access can set this reference for you if you use a Microsoft Office 8.0 Object Library constant to set an Assistant object's property or as an argument to an Assistant object's method.

See Also

Assistant object, Item property (Assistant, BalloonLabel, and BalloonCheckbox objects) ("Microsoft Office Language Reference" in Volume 5).

Example

The following example uses the Assistant property of the Application object to manipulate various properties and methods of the Assistant object. To try this example, paste the following code into the Declarations section of a standard module. Create a reference to the Microsoft Office 8.0 Object Library by using the References dialog box, available by clicking References on the Tools menu. Then click anywhere inside the procedure and press F5 to run it.

Sub AnimateAssistant() Dim blnState As Boolean With Assistant ' Save Assistant's visible state. blnState = .Visible ' Make Assistant visible. If blnState = False Then .Visible = True ' Animate Assistant. .Animation = msoAnimationAppear ' Display Assistant object's Item and FileName properties. MsgBox "Hello, my name is " & .Item & ". I live in " & .FileName, , _ "Assistant Information:"

Setting Description

application Optional. The Application object.

Assistant Required. When used without specifying a method or property, returns the Assistant object's Item property.

method or property

A method or property of the Assistant object.

Page 58: Microsoft Access Language

Microsoft Access Language Reference Página 58 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' Return Assistant's visible state to original setting. .Visible = blnState End WithEnd Sub

AutoActivate Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

You can use the AutoActivate property to specify how the user can activate an OLE object.

Setting

The AutoActivate property uses the following settings.

You can set this property by using the control's property sheet, a macro, or Visual Basic.

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,

Setting Description Constant

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 by using Visual Basic to set the control's Action property to acOLEActivate.

acOLEActivateManual

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.

acOLEActivateGetFocus

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.

acOLEActivateDoubleClick

Page 59: Microsoft Access Language

Microsoft Access Language Reference Página 59 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

see the documentation for the application that was used to create the object for information about using this feature.

With 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.

See Also

Action property, OLEType property.

AutoCenter Property

Applies To

Form.

Description

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.

You can set this property by using 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

Setting Description Visual Basic

Yes The form will be centered automatically on opening.

True (–1)

No (Default) The form's upper-left corner will be in the same location as when the form was last saved.

False (0)

Page 60: Microsoft Access Language

Microsoft Access Language Reference Página 60 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

opened makes it easier to view and use.

If you make any changes in Design view to a form whose AutoResize property is set to No and whose AutoCenter property is set to Yes, you should switch to Form view before saving the form. If you don't, Microsoft Access clips the form on the right and bottom edges the next time you open the form.

See Also

AutoResize property, MoveSize action.

AutoExpand Property

Applies To

Combo Box control.

Description

You can use the AutoExpand property to specify whether Microsoft Access automatically fills the text box portion of a combo box with a value from the combo box list that matches the characters you enter 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 uses the following settings.

You can set the AutoExpand property by using the combo box's property sheet, a macro, or Visual Basic.

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)

Page 61: Microsoft Access Language

Microsoft Access Language Reference Página 61 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

When the LimitToList property is set to Yes and the combo box list is dropped down, Microsoft Access selects matching values in the list as the user enters characters in the text box portion of the combo box, even if the AutoExpand property is set to No. If the user presses ENTER or moves to another control or record, the selected value appears in the combo box.

AutoLabel Property

See AddColon, AutoLabel Properties.

AutoRepeat Property

Applies To

Command Button control.

Description

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 in.

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 in.

True (–1)

No (Default) The macro or event procedure runs once.

False (0)

Page 62: Microsoft Access Language

Microsoft Access Language Reference Página 62 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the command button's 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.

If the code attached to the command button causes the current record to change, the AutoRepeat property has no effect.

If the code attached to the command button causes changes to another control on a form, use the DoEvents function to ensure proper screen updating.

See Also

DoEvents function.

AutoResize Property

Applies To

Form.

Description

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

False (0)

Page 63: Microsoft Access Language

Microsoft Access Language Reference Página 63 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using 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 you make any changes in Design view to a form whose AutoResize property is set to No and whose AutoCenter property is set to Yes, you should switch to Form view before saving the form. If you don't, 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.

See Also

AutoCenter property, MoveSize action.

AutoTab Property

Applies To

Text Box control.

Description

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.

form, it will be the saved window size.

Setting Description Visual Basic

Yes Generates a tab when the last allowable character in a text box is entered.

True (–1)

Page 64: Microsoft Access Language

Microsoft Access Language Reference Página 64 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using a form's property sheet, a macro, or Visual Basic.

You can set the default for this property by using the control's default control style or the DefaultControl method in Visual Basic.

The AutoTab property affects tab behavior in both Form view and Datasheet view.

Remarks

You create an input mask for a control by 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.

See Also

Cycle property, InputMask property, TabIndex property, TabStop property.

BackColor Property

Applies To

Bound Object Frame control, Chart control, Combo Box control, Form section, Image control, Label control, List Box control, Option Group control, Rectangle control, Report section, Text Box control, Unbound Object Frame control.

Description

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's or section's interior.

You can use the Color Builder to set this property by clicking the Build button to the right of the property box in the property sheet. Using the Color Builder enables you to define custom back

No (Default) Doesn't generate a tab when the last allowable character in a text box is entered.

False (0)

Page 65: Microsoft Access Language

Microsoft Access Language Reference Página 65 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

colors for controls or sections.

You can also set this property by using the Fill/Back Color button on the Formatting (Form/Report) toolbar, a control's or section's property sheet, a macro, or Visual Basic.

In Visual Basic, use a numeric expression to set this property. This property setting has a data type of Long.

You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

For TableDef or QueryDef objects you can set this property using the Fill/Back Color button on the Formatting (Datasheet) toolbar, or in Visual Basic by using the DatasheetBackColor property.

Remarks

To use the BackColor property, the BackStyle property, if available, must be set to Normal.

See Also

BackStyle property, BorderColor property, DatasheetBackColor, DatasheetForeColor properties, DatasheetCellsEffect property, DatasheetFontItalic, DatasheetFontUnderline properties, DatasheetFontName, DatasheetFontHeight properties, DatasheetFontWeight property, DatasheetGridlinesBehavior property, DatasheetGridlinesColor property, DrawMode property, DrawStyle property, DrawWidth property, FillColor property, ForeColor property, PSet method, QBColor function, RGB function.

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 IfEnd Sub

Page 66: Microsoft Access Language

Microsoft Access Language Reference Página 66 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

BackStyle Property

Applies To

Bound Object Frame control, Chart control, Combo Box control, Image control, Label control, Option Group control, Rectangle control, Tab control, Text Box control, Unbound Object Frame control.

Description

You can use the BackStyle property to specify whether a control will be transparent.

Setting

The BackStyle property uses the following settings.

You can set this property by using the Fill/Back Color button on the Formatting (Form/Report) toolbar, a control's property sheet, a macro, or Visual Basic.

You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

Remarks

If the Transparent button on the Back Color button 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.

See Also

BackColor property, SpecialEffect property.

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

Page 67: Microsoft Access Language

Microsoft Access Language Reference Página 67 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Beep Action

Description

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

Setting

The Beep action doesn't have any arguments.

Remarks

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

l Important screen changes have occurred.l The wrong kind of data has been entered in a control. For example, the user has entered

numeric data in a text box control.l 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.

See Also

Beep method, MsgBox action, ValidationRule, ValidationText properties.

Beep Method

Applies To

DoCmd object.

Description

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 has no arguments.

Page 68: Microsoft Access Language

Microsoft Access Language Reference Página 68 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

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

See Also

Beep action, Beep statement, DoCmd object, MsgBox action.

BeforeDelConfirm Event

See Delete, BeforeDelConfirm, AfterDelConfirm Events.

BeforeInsert, AfterInsert Events

Applies To

Form.

Description

l The BeforeInsert event occurs when the user types the first character in a new record, but before the record is actually created.

l The AfterInsert event occurs after a new record is added.

Note Setting the value of a control by using a macro or Visual Basic doesn't trigger these events.

Remarks

To run a macro or event procedure when these events occur, set the BeforeInsert or AfterInsert property to the name of the macro or to [Event Procedure].

You can use an AfterInsert event procedure or macro to requery a recordset whenever a new record is added.

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.

Page 69: Microsoft Access Language

Microsoft Access Language Reference Página 69 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

BeforeUpdate, AfterUpdate events, Change event, Current event, Delete, BeforeDelConfirm, AfterDelConfirm events, Event properties, GoToRecord action, Open, Close events.

BeforeInsert, AfterInsert Events — Event Procedures

Description

To create an event procedure that runs 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 has the following argument.

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.

Argument Description

Page 70: Microsoft Access Language

Microsoft Access Language Reference Página 70 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can't cancel the AfterInsert event.

See Also

BeforeInsert, AfterInsert events — macros.

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 the example, add the following event procedure to a form named Employees that is based on a table or query. Switch to form Datasheet view and try to insert a record.

Private Sub Form_BeforeInsert(Cancel As Integer) If MsgBox("Insert new record here?", vbOKCancel) = vbCancel Then Cancel = True End IfEnd Sub

Private Sub Form_AfterInsert() Forms!Employees.RequeryEnd Sub

BeforeInsert, AfterInsert Events — Macros

Description

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.

See Also

Cancel The setting determines if the BeforeInsert event occurs. Setting the Cancel argument to True (–1) cancels the BeforeInsert event.

Page 71: Microsoft Access Language

Microsoft Access Language Reference Página 71 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

BeforeInsert, AfterInsert events — event procedures.

BeforeUpdate, AfterUpdate Events

Applies To

Bound Object Frame control, Check Box control, Combo Box control, Form, List Box control, Option Button control, Option Group control, Text Box control, Toggle Button control.

Description

l The BeforeUpdate event occurs before changed data in a control or record is updated.l The AfterUpdate event occurs after changed data in a control or record is updated.

Notes

l Changing data in a control by using Visual Basic or a macro containing the SetValue action 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.

l The BeforeUpdate and AfterUpdate events apply only to controls on a form, not controls on a report.

l 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

To run a macro or event procedure when these events occur, set the BeforeUpdate, or AfterUpdate property to the name of the macro or to [Event Procedure].

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 clicks Save Record on the Records 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 clicking Save Record on the Records menu, the BeforeUpdate and AfterUpdate events for the form occur immediately after the BeforeUpdate and AfterUpdate events for the control. When you move to a different record, the Exit and LostFocus events for the control 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 by using the Save Record command on the Records 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 one or more controls in the record.

Page 72: Microsoft Access Language

Microsoft Access Language Reference Página 72 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 for the form occurs. Even if the user enters a new value in the control, the OldValue property setting isn't changed until the data is saved (the record is updated). 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:

l Involve conditions for more than one value on a form.l Display different error messages for different data entered.l Can be overridden by the user.l 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.

See Also

Enter, Exit events, Event properties, Required property, SetValue action, ValidationRule, ValidationText properties.

BeforeUpdate, AfterUpdate Events — Event Procedures

Description

To create an event procedure that runs 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 has the following arguments.

Page 73: Microsoft Access Language

Microsoft Access Language Reference Página 73 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The AfterUpdate event procedure has the following argument.

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.

See Also

BeforeUpdate, AfterUpdate events — macros.

Example

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

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

Private Sub ProductName_BeforeUpdate(Cancel As Integer) If(Not IsNull(DLookup("[ProductName]", "Products", _

Argument Description

controlname The name of the control whose BeforeUpdate event procedure you want to run.

Cancel The setting determines if the BeforeUpdate event occurs. Setting the Cancel argument to True (–1) cancels the BeforeUpdate event.

Argument Description

controlname The name of the control whose AfterUpdate event procedure you want to run.

Page 74: Microsoft Access Language

Microsoft Access Language Reference Página 74 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

"[ProductName] ='" & Me!ProductName & "'"))) Then MsgBox "Product has already been entered in the database." Cancel = True Me!ProductName.Undo End IfEnd Sub

BeforeUpdate, AfterUpdate Events — Macros

Description

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 to cancel the AfterUpdate event.

See Also

BeforeUpdate, AfterUpdate events — event procedures.

Bookmark Property

Applies To

Page 75: Microsoft Access Language

Microsoft Access Language Reference Página 75 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Form.

Description

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 set this property by using a macro or Visual Basic.

Note You get or set the form's Bookmark property separately from the DAO Bookmark property of the underlying table or query.

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. You can use the StrComp function to compare a Variant or string variable to a bookmark, or when comparing a bookmark against a bookmark. The third argument for the StrComp function must be set to a value of zero.

Note Bookmarks are not saved with the records they represent and are only valid while the form is open. 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 to 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 by 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 can use the FindFirst method with the form's RecordsetClone property.

An error occurs if you set the Bookmark property to a string variable and then try to return to that record after the record has been deleted.

Page 76: Microsoft Access Language

Microsoft Access Language Reference Página 76 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The value of the Bookmark property isn't the same as a record number.

See Also

Bookmark property ("DAO Language Reference"), Bookmarkable property ("DAO Language Reference"), RecordsetClone property.

Example

To test the following example with the Northwind sample database, you need to add a command button named cmdFindContactName to the Suppliers form, and then add the following code to the button's Click event. When the button is clicked, the user is asked to enter a portion of the contact name to find. If the name is found, the form's Bookmark property is set to the Recordset object's DAO Bookmark property, which moves the form's current record to the found name.

Private Sub cmdFindContactName_Click() Dim rst As Recordset, strCriteria As String strCriteria = "[ContactName] Like '*" & InputBox("Enter the " _ & "first few letters of the name to find") & "*'"

Set rst = Me.RecordsetClone rst.FindFirst strCriteria If rst.NoMatch Then MsgBox "No entry found" Else Me.Bookmark = rst.Bookmark End IfEnd Sub

BorderColor Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Rectangle control, Subform/Subreport control, Text Box control, Unbound Object Frame control.

Description

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 box in the property sheet. Using the Color Builder enables you to define custom border colors for controls.

You can also set this property by using the Line/Border Color button on the Formatting (Form/Report) toolbar, a macro, or Visual Basic.

Page 77: Microsoft Access Language

Microsoft Access Language Reference Página 77 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

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.

See Also

BorderStyle property, BorderWidth property, ForeColor property, QBColor function, RGB function, SpecialEffect property.

Example

See the BackColor property example.

BorderStyle Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Form, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Rectangle control, Subform/Subreport control, Text Box control, Unbound Object Frame control.

Description

l Forms. You can use the BorderStyle property to specify the type of border and border elements (title bar, Control menu, Minimize and Maximize buttons, or Close button) to use for the form. You typically use different border styles for normal forms, pop-up forms, and custom dialog boxes.

l Controls. 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. The form isn't resizable.

0

Page 78: Microsoft Access Language

Microsoft Access Language Reference Página 78 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

You can set the BorderStyle property for a form only in form Design view by using the form's property sheet, a macro, or Visual Basic.

For controls, the BorderStyle property uses the following settings.

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 (double) border and can include only a title bar, a Close button, 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

Page 79: Microsoft Access Language

Microsoft Access Language Reference Página 79 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the BorderStyle property for a control by using the control's property sheet, a macro, or Visual Basic.

You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

Remarks

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.

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, CloseButton, MinMaxButtons, ScrollBars, NavigationButtons, and RecordSelectors properties. These properties interact in the following

Setting Description Visual Basic

Transparent (Default only for label, chart, 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

Page 80: Microsoft Access Language

Microsoft Access Language Reference Página 80 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ways:

l 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.

l If the BorderStyle property is set to None, the form doesn't have a Control menu, regardless of its ControlBox property setting.

l The BorderStyle property setting doesn't affect the display of the scroll bars, navigation buttons, the record number box, or record selectors.

The BorderStyle property takes effect only in Form view. The property setting is ignored in form Design 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 in Visual Basic 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 action argument of the OpenForm action to open a form with its Modal and PopUp properties set to Yes.

See Also

BackStyle property, BorderColor property, BorderWidth property, ControlBox property, ForeColor property, MinMaxButtons property, Modal property, PopUp property, SpecialEffect property.

BorderWidth Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Rectangle control, Subform/Subreport control, Text Box control, Unbound Object Frame control.

Description

You can use the BorderWidth property to specify the width of a control's border.

Setting

The BorderWidth property uses the following settings.

Page 81: Microsoft Access Language

Microsoft Access Language Reference Página 81 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the Line/Border Width button on the Formatting (Form/Report) toolbar, the control's property sheet, a macro, or Visual Basic.

You can set the default for this property by using the control's default control style or the DefaultControl method in Visual Basic.

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. If the SpecialEffect property is set to any other value and/or the BorderStyle property is set to Transparent, and you set the BorderWidth property, the SpecialEffect property is automatically reset to Flat and the BorderStyle property is automatically reset to Solid.

The exact border width depends on your computer and printer. On some systems, the hairline and 1-point widths appear the same.

See Also

BackStyle property, BorderColor property, BorderStyle property, SpecialEffect property.

BoundColumn Property

Applies To

Combo Box control, List Box control, Table field.

Description

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 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

Page 82: Microsoft Access Language

Microsoft Access Language Reference Página 82 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the BoundColumn property by using the control's property sheet, a macro, or Visual Basic.

For table fields, you can set this property on the Lookup tab in the Field Properties section of table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Tip Microsoft Access sets the BoundColumn 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 by using a number or a numeric expression equal to a value from 0 to the setting of the ColumnCount property.

Remarks

The leftmost visible column in a combo box (the leftmost column whose setting in the combo box's ColumnWidths property is not 0) 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's value in the text box or combo box list 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 (or if you set the BoundColumn property to 0), the LimitToList property is set to Yes.

Microsoft Access uses zero-based numbers to refer to columns in the Column property. That is, the first column is referenced by using the expression Column(0); the second column is referenced by using the expression Column(1); and so on. However, the BoundColumn property

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 is 1) The value in the specified column becomes the control's value. If the control is bound to a field, then this setting is stored in that field in the current record. The BoundColumn property can't be set to a value larger than the setting of the ColumnCount property.

Page 83: Microsoft Access Language

Microsoft Access Language Reference Página 83 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

uses 1-based numbers to refer to the columns. This means that if the BoundColumn property is set to 1, you could access the value stored in that column by using the expression Column(0).

If the AutoExpand property is set to Yes, Microsoft Access automatically fills in a value in the text box portion of the combo box that matches a value in the combo box list as you type.

See Also

AutoExpand property, Column property, ColumnCount property, ColumnHeads property, ColumnWidths property, ControlSource property, LimitToList property, ListRows property, ListWidth property, MultiSelect property, RowSourceType, RowSource properties, Selected property, Value property.

BuildCriteria Method

Applies To

Application object.

Description

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 string expression argument for the Filter property.

Syntax

application.BuildCriteria(field, fieldtype, expression)

The BuildCriteria method has the following arguments.

Argument Description

application (Optional) The Application object.

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 DAO Type property.

Page 84: Microsoft Access Language

Microsoft Access Language Reference Página 84 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 row 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 preceding correctly parsed string, you can supply the following arguments to the BuildCriteria method:

Dim strCriteria As StringstrCriteria = 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 that refers 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.

See Also

Filter property.

Example

expression A string expression identifying the criteria to be parsed.

Page 85: Microsoft Access Language

Microsoft Access Language Reference Página 85 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The following example prompts the user to enter the first few letters of a product's name and 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 object 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 = TrueEnd Sub

BuiltIn Property

Applies To

Reference object.

Description

The BuiltIn property returns a Boolean value indicating whether a Reference object points to a default reference that's necessary for Microsoft Access to function properly.

Setting

The BuiltIn property is available only by using Visual Basic and is read-only.

The BuiltIn property returns the following values.

Value Description

True (–1) The Reference object refers to a default reference that can't be removed.

False (0) The Reference object refers to a nondefault reference that isn't necessary for Microsoft Access to function properly.

Page 86: Microsoft Access Language

Microsoft Access Language Reference Página 86 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The default references in Microsoft Access include the Microsoft Access 8.0 object library and the Visual Basic For Applications library.

See Also

Reference object, References collection.

Example

The following example prints the default references in the References collection:

Sub ReferenceBuiltInOnly() Dim ref As Reference

' Enumerate through References collection. For Each ref In References ' Check BuiltIn property. If ref.BuiltIn = True Then Debug.Print ref.Name End If Next refEnd Sub

Cancel Property

Applies To

ActiveX control, Command Button control.

Description

You can use the Cancel property to specify whether a command button is also the Cancel button on a form.

Setting

The Cancel property uses 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)

Page 87: Microsoft Access Language

Microsoft Access Language Reference Página 87 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the command button's property sheet, a macro, or Visual Basic.

Remarks

Setting the Cancel property to Yes makes the command button the Cancel button in the form. However, you must still write the macro or Visual Basic event procedure that performs whatever action or actions you want the Cancel button to carry out (for example, closing the form without saving any changes to it). Set the command button's OnClick event property to the name of the macro or event procedure.

When a command button's Cancel property setting is Yes and the Form window is active, the user can choose the command button by pressing ESC, by 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 will be restored.

When the Cancel property is set to Yes for one command button on a form, 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 Cancel property and the Default property to Yes.

See Also

Click event, Default property.

CancelEvent Action

Description

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 have 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 use this action with the MsgBox action to indicate that the data has failed the

Page 88: Microsoft Access Language

Microsoft Access Language Reference Página 88 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Note You can use the CancelEvent action with the MouseDown event only to cancel the event that occurs when you right-click an object.

If a control's OnDblClick event property setting specifies a macro containing the CancelEvent action, the action cancels the DblClick 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 to be carried out or open the macro and delete the CancelEvent action. 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.

See Also

CancelEvent method, StopMacro action.

CancelEvent Method

Applies To

l ApplyFilter l BeforeDelConfirm l BeforeInsert

l BeforeUpdate l DblClick l Delete

l Exit l Filter l Format

l KeyPress l MouseDown l NoData

l Open l Print l Unload

Page 89: Microsoft Access Language

Microsoft Access Language Reference Página 89 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DoCmd object.

Description

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 has no arguments.

Remarks

The CancelEvent method has an effect only when it's 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 right-clicking only) can be canceled only in macros, not event procedures, so you must use the CancelEvent action in a macro to cancel these events.

See Also

CancelEvent action, DoCmd object.

CanGrow, CanShrink Properties

Applies To

Form section, Report section, Subform/Subreport control, Text Box control.

Description

You can use the CanGrow and CanShrink properties to control the appearance of sections or controls on forms and reports that are printed or previewed. For example, if you set both properties to Yes, a section or control automatically adjusts vertically to print or preview all the data the section or control contains.

Notes

l The CanGrow and CanShrink properties don't apply to form or report page header and page footer sections, although they do apply to controls in such sections.

l These properties affect the display of form sections and controls only when the form is printed or previewed, not when the form is displayed in Form view, Datasheet view, or Design view.

Setting

Page 90: Microsoft Access Language

Microsoft Access Language Reference Página 90 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The CanGrow property uses the following settings.

The CanShrink property uses the following settings.

You can set these properties only by using the section or control's property sheet.

For controls, you can set the default for these properties by using the default control style or the DefaultControl method in Visual Basic.

These property settings are read-only in a macro or Visual Basic in any view but Design view.

Remarks

You can use these properties to control the appearance of printed forms and reports. When you set both properties to Yes, the object automatically adjusts so any amount of data can be printed. When a control grows or shrinks, the controls below it move down or up the page.

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. (However, if you set a control's CanShrink

Setting Description Visual Basic

Yes The section or control grows vertically so that all data it contains can be printed or previewed.

True (–1)

No (Default) The section or control doesn't grow. Data that doesn't fit within the fixed size of the section or control won't be printed or previewed.

False (0)

Setting Description Visual Basic

Yes The section or control shrinks vertically so that the data it contains can be printed or previewed without leaving blank lines.

True

No (Default) The section or control doesn't shrink.

False

Page 91: Microsoft Access Language

Microsoft Access Language Reference Página 91 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

property to Yes, Microsoft Access doesn't set the section's CanShrink property to Yes.)

Sections grow and shrink vertically across their entire width. For example, suppose a form has two text boxes side by side in a section, and each control has its CanShrink property set to Yes. If one text box contains one line of data and the other text box contains two lines of data, both text boxes will be two lines long because the section is sized across its entire width. To grow and shrink the data independently, you can place two subform or subreport controls side by side, and set their CanGrow and CanShrink properties to Yes.

When you use the CanGrow and CanShrink properties, remember that:

l The property settings don't affect the horizontal spacing between controls; they affect only the vertical space the controls occupy.

l Overlapping controls can't grow or shrink.l The height of a large control can prevent controls beside it from shrinking. For example, if

several short controls are on the left side of a report's detail section and one tall control, such as an unbound object frame, is on the right side, the controls on the left won't shrink, even if they contain no data.

See Also

Format event, Retreat event.

Caption Property

Applies To

Command Button control, Field object, Form, Label control, Page, Query field, Report, Table field, Toggle Button control.

Description

You can use the Caption property to provide helpful information to the user through captions on objects in various views:

l Field captions specify 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.

l Form captions specify the text that appears in the title bar in Form view.l Report captions specify the title of the report in Print Preview.l Button and label captions specify the text that appears in the control.

Setting

The Caption property is a string expression that can contain up to 2,048 characters. Captions for forms and reports that are too long to display in the title bar are truncated.

For controls, you can set this property by using the property sheet. For fields, you can set this property by using the property sheet in table Design view or in the Query window (in the Field Properties property sheet). You can also set this property by using a macro or Visual Basic.

Page 92: Microsoft Access Language

Microsoft Access Language Reference Página 92 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 label attached to a control or as the column heading in Datasheet view. If you don't specify the caption for a query field, the caption 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.

Note The text of the Caption property for a label or command button control is the hyperlink display text when the HyperlinkAddress or HyperlinkSubAddress property is set for the control.

You can use the Caption property to assign an access key to a label or command button. In the caption, include an ampersand (&) immediately preceding the character you want to use as an access key. The character will be underlined. You can press ALT plus the underlined character to move the focus to that control on a form.

Tip Include two ampersands (&&) in the setting for a 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.

See Also

Description property, Description property ("DAO Language Reference"), FieldName property, HyperlinkAddress property, Name property.

Change Event

Applies To

Combo Box control, Tab control, Text Box control.

Description

The Change event occurs when the contents of a text box or the text portion of a combo box changes. It also occurs when you move from one page to another page in a tab control. Examples of this event include entering a character directly in the text box or combo box or changing the control's Text property setting by using a macro or Visual Basic.

Notes

l Setting the value of a control by 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.

l This event applies only to controls on a form, not controls on a report.

Page 93: Microsoft Access Language

Microsoft Access Language Reference Página 93 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

To run a macro or event procedure when this event occurs, set the OnChange property to the name of the macro or to [Event Procedure].

By running a macro or 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 — 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:

l If possible, avoid attaching a Change macro or event procedure to a control that alters the control's contents.

l Avoid creating two or more controls having Change events that affect each other — for example, two text boxes that update each other.

Changing the data in a text box or combo box by 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 therefore after all of the Change events for the control.

In combo boxes for which the LimitToList property is set to Yes, the NotInList event occurs after you enter a value that isn't 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.

See Also

BeforeUpdate, AfterUpdate events, Enter, Exit events, Event properties, GotFocus, LostFocus events, KeyDown, KeyUp events, KeyPress event, NotInList event, Open, Close events, Text property.

Change Event — Event Procedures

Description

Page 94: Microsoft Access Language

Microsoft Access Language Reference Página 94 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To create an event procedure that runs 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 has the following argument.

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 (for example, by setting the control's Text property). 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.

See Also

Change event — macros.

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 the example, add the following event procedure to a form named Orders that contains a text box named 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 more than three, reset value of text box. If intLetter < 3 Then intLetter = intLetter + 1 Else MsgBox "Only three characters are allowed." intLetter = 0 Forms!Orders!ShipRegion.Undo End IfEnd Sub

Argument Description

controlname The name of the control whose Change event procedure you want to run.

Page 95: Microsoft Access Language

Microsoft Access Language Reference Página 95 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Change Event — Macros

Description

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.

See Also

Change event — event procedures.

Circle Method

Applies To

Report object.

Description

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 for a report section, or the OnPage event property for a report.

The Circle method has the following arguments.

Argument Description

object The Report object on which the circle is drawn.

Page 96: Microsoft Access Language

Microsoft Access Language Reference Página 96 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Step A keyword that indicates 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 the object argument.

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 the Report object specified by the object argument 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 the Report object specified by the object argument 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, the start and end arguments specify (in radians) the beginning and end positions of the arc. The default value for the start argument is 0 radians; the default for the end argument is 2 pi radians. The range for both is –2 pi radians to 2 pi radians.

aspect A Single value indicating the aspect ratio of the circle. The default value is 1.0, which yields a perfect (nonelliptical) circle on any screen.

Page 97: Microsoft Access Language

Microsoft Access Language Reference Página 97 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

When drawing a partial circle or ellipse, if the start argument is negative, the Circle method draws a radius to the position specified by the start argument and treats the angle as positive. If the end argument is negative, the Circle method draws a radius to the position specified by the end argument 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 the start argument rather than 0. For example, you might specify –.00000001 for the start argument.

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 x and y arguments.

See Also

CurrentX, CurrentY properties, DrawMode property, DrawStyle property, DrawWidth property, Event properties, FillColor property, FillStyle property, ForeColor property, QBColor function, RGB function, ScaleHeight, ScaleWidth properties, ScaleLeft, ScaleTop properties, ScaleMode property.

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. 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 Dim 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. ' Draw circle. Me.Circle(sngHCtr, sngVCtr), sngRadius 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.

Page 98: Microsoft Access Language

Microsoft Access Language Reference Página 98 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Me.FillStyle = 0 ' Fill pie slice. ' Draw pie slice within circle. Me.Circle(sngHCtr, sngVCtr), sngRadius, , sngStart, sngEndEnd Sub

Class Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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 supplied by you or Microsoft Access when you create or paste an OLE object.

You can set the Class property by using the control's property sheet, a macro, or Visual Basic.

Remarks

A class name defines the type of OLE object. For example, Microsoft Excel 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 by clicking Paste Special on the Edit menu or Object 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 by using Visual Basic to set the control's Action property to acOLEPaste or acOLEPasteSpecialDlg.

Note The OLEClass property and the Class property are similar but not identical. The OLEClass property setting is a general description of the OLE object whereas 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.

See Also

Action property, OLEClass property.

Example

Page 99: Microsoft Access Language

Microsoft Access Language Reference Página 99 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See the Action property example.

Click Event

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Form section, Image control, Label control, List Box control, Option Button control, Option Group control, Page, Rectangle control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

The Click event occurs when the user presses and then releases a mouse button over an object.

Notes

l The Click event applies only to forms, form sections, and controls on a form, not controls on a report.

l 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.

l 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.

l This event applies to a control containing a hyperlink.

Remarks

To run a macro or event procedure when this event occurs, set the OnClick property to the name of the macro or to [Event Procedure].

On a form, this event occurs when the user clicks a blank area or record selector on the form.

For a control, this event occurs when the user:

l Clicks a control with the left mouse button. Clicking a control with the right or middle mouse button does not trigger this event.

l Clicks a control containing hyperlink data with the left mouse button. Clicking a control with the right or middle mouse button does not trigger this event. When the user moves the mouse pointer over a control containing hyperlink data, the mouse pointer changes to a "hand" icon. When the user clicks the mouse button, the hyperlink is activated, and then the Click event occurs.

l 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.

l Presses SPACEBAR when a command button, check box, option button, or toggle button has the focus.

l Presses the ENTER key on a form that has a command button whose Default property is set

Page 100: Microsoft Access Language

Microsoft Access Language Reference Página 100 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

to Yes.l Presses the ESC key on a form that has a command button whose Cancel property is set to

Yes.l 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 command-like actions. For the other applicable controls, use this event to trigger actions in response to one of the occurrences discussed earlier in this topic.

For a command button only, Microsoft Access runs the macro or event procedure specified by the OnClick property when the user chooses the command button by pressing the ENTER key or an access key. The macro or event procedure runs once. If you want the macro or event procedure 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 by using the mouse button to trigger the Click event.

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.

Double-clicking a control causes both the DblClick and Click events to occur. For command buttons, double-clicking triggers the following events, in this order:

MouseDown MouseUp 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.

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.

Tip To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.

See Also

AutoRepeat property, Cancel property, Caption property, DblClick event, Default property, Event properties, MouseDown, MouseUp events.

Click Event — Event Procedures

Description

To create an event procedure that runs when the Click event occurs, set the OnClick property to [Event Procedure], and click the Build button.

Syntax

Page 101: Microsoft Access Language

Microsoft Access Language Reference Página 101 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Private Sub Form_Click( )

Private Sub controlname_Click( )

The Click event procedure has the following argument.

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.)

You can't cancel the Click event.

See Also

Click event — macros.

Example

In the following 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 example, add the following event procedure to a form that contains a check box called ReadOnly and a text box named Amount.

Private Sub ReadOnly_Click() With Me!Amount If Me!ReadOnly = True Then ' If checked. .Enabled = False ' Disable editing. .Locked = True Else ' If cleared. .Enabled = True ' Enable editing. .Locked = False End If End WithEnd Sub

Argument Description

controlname The name of the control whose Click event procedure you want to run.

Page 102: Microsoft Access Language

Microsoft Access Language Reference Página 102 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Click Event — Macros

Description

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.

You can't use the CancelEvent action in a Click macro to cancel the Click event.

See Also

Click event — event procedures.

Close Action

Description

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 has 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 Object Type box in the Action Arguments section of the Macro window. To select the active window, leave this argument blank.

Page 103: Microsoft Access Language

Microsoft Access Language Reference Página 103 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Close method, Open, Close events, Quit action.

Close Event

See Open, Close Events.

Close Method

Applies To

DoCmd object.

Description

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

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

Page 104: Microsoft Access Language

Microsoft Access Language Reference Página 104 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 has the following arguments.

Remarks

If you leave the objecttype and objectname arguments blank (the default constant, acDefault, is assumed for objecttype), 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.

See Also

Argument Description

objecttype One of the following intrinsic constants:

acDefault (default)acFormacMacroacModuleacQueryacReportacTable

objectname A string expression that's the valid name of an object of the type selected by the objecttype argument.

save One of the following intrinsic constants:

acSaveNoacSavePrompt (default)acSaveYes

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

Page 105: Microsoft Access Language

Microsoft Access Language Reference Página 105 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Close action, Close method, Open, Close events, Quit method (DoCmd object), Save method.

Example

The following 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

CloseButton Property

Applies To

Form.

Description

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.

You can set the CloseButton property by using the form's property sheet, a macro, or 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 appears dimmed (grayed), 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.

Tip You can also close the form by pressing ALT+F4.

See Also

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)

Page 106: Microsoft Access Language

Microsoft Access Language Reference Página 106 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

BorderStyle property, ControlBox property, MinMaxButtons property.

CloseCurrentDatabase Method

Applies To

Application object.

Description

You can use the CloseCurrentDatabase method to close the current database from another application that has opened a database through 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 has the following argument.

Remarks

The CloseCurrentDatabase method is useful when you have opened a Microsoft Access database from another application through 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 DAO Close method. The DAO Close method closes a Database object variable, causing the variable to go out of scope, but it doesn't actually close the database that is open in the Microsoft Access window. The CloseCurrentDatabase method closes the database that is open in the Microsoft Access window.

See Also

NewCurrentDatabase method, OpenCurrentDatabase method.

Argument Description

application The Application object.

Page 107: Microsoft Access Language

Microsoft Access Language Reference Página 107 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

The following example opens a Microsoft Access database from another application through 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 ActiveX component. 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.Dim appAccess As Access.Application

Sub CreateForm() Const strConPathToSamples = _ "C:\Program Files\Microsoft Office\Office\Samples\"

Dim frm As Form, strDB As String

' Initialize string to database path. strDB = strConPathToSamples & "Northwind.mdb" ' Create new instance of Microsoft Access. Set appAccess = CreateObject("Access.Application.8") ' 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 Set AppAccess = NothingEnd Sub

CodeContextObject Property

Applies To

Application object.

Description

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 in all views.

Remarks

The ActiveForm and ActiveReport properties of the Screen 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

Page 108: Microsoft Access Language

Microsoft Access Language Reference Página 108 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

or Visual Basic code is currently running, for example, when Visual Basic code runs in the Timer event on a hidden form.

See Also

ActiveForm property, ActiveReport property, Application object, Me property, Screen object.

Example

In the following example the CodeContextObject property is used in a function to identify the name of the object in which an error occurred. 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 command button's 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 IfEnd 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 = 0End Function

CodeDb Function

Description

You can use the CodeDb function in a code module to determine the name of the Database object that refers to the database in which code is currently running. Use the CodeDb function to access Data Access Objects (DAO) 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.

Page 109: Microsoft Access Language

Microsoft Access Language Reference Página 109 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The CodeDb function returns a Database object for which the Name property is the full path and 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 running 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 example, 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 run from the current database, it returns the name of the current database, which is the same value returned by the CurrentDb function.

See Also

CurrentDb 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 running. 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 running. Set dbs = CodeDb ' Create table-type Recordset object. Set rst = dbs.OpenRecordSet("Errors", dbOpenTable) ' Set index to primary key (ErrorID field). rst.Index = "PrimaryKey" ' Find error number passed to GetErrorString function. rst.Seek "=", intError ' Return associated error message. GetErrorString = rst.Fields!ErrorData.Value rst.CloseEnd Function

Argument Description

database A Database object variable.

Page 110: Microsoft Access Language

Microsoft Access Language Reference Página 110 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Collection Property

Applies To

Reference object.

Description

The Collection property returns a reference to the collection that contains an object.

Setting

The Collection property is available only by using Visual Basic and is read-only.

Remarks

You can use the Collection property to access the collection to which an object belongs. For example, the Collection property of a Reference object returns an object reference to the References collection.

The Collection property is similar to the Parent property.

See Also

Parent property, Reference object.

Column Property

Applies To

Combo Box control, List Box control.

Description

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

control.Column(column, row)

The Column property uses the following settings.

Page 111: Microsoft Access Language

Microsoft Access Language Reference Página 111 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property setting is only available by using a macro or Visual Basic. This property setting isn't available in Design view and is read-only in other views.

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."End If

Note To determine how many columns a combo box or list box has, you can inspect the ColumnCount property setting.

See Also

BoundColumn property, ColumnCount property, ColumnHeads property, ColumnWidths property, ListCount property, MultiSelect property, Nz function, Selected property.

Example

The following example uses the Column property and the ColumnCount property to print the values of a list box selection.

Sub Read_ListBox() Dim intNumColumns As Integer, inti As Integer Dim frmCust As Form

Setting Description

control A Control object that represents the active combo box or list box control.

column An integer that can range from 0 to the setting of the ColumnCount property minus one.

row Optional. An integer that can range from 0 to the setting of the ListCount property minus 1.

Page 112: Microsoft Access Language

Microsoft Access Language Reference Página 112 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Set frmCust = Forms!frmCustomers If frmCust!lstCustomerNames.ItemsSelected.Count > 0 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 inti = 0 To intNumColumns - 1 ' Print column data. Debug.Print frmCust!lstCustomerNames.Column(inti) Next inti Else Debug.Print "You haven't selected an entry in the list box." End IfEnd Sub

ColumnCount Property

Applies To

Chart control, Combo Box control, List Box control, Table field, Unbound Object Frame control.

Description

You can use the ColumnCount property to specify the number of columns displayed in a list box or in the list box portion of a combo box, or sent to OLE objects in a chart control or unbound 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, or the maximum number of values in the value list, specified in the RowSource property of the control.

You can set the ColumnCount property by using the control's property sheet, a macro, or Visual Basic.

For table fields, you can set this property on the Lookup tab in the Field Properties section of table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Tip Microsoft Access sets the ColumnCount 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.

Page 113: Microsoft Access Language

Microsoft Access Language Reference Página 113 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

If the RowSource property contains a list of values (the RowSourceType property is set to Value List), the values are put into the rows and columns of the combo box or list box in the order they are listed in the RowSource property. For example, if the RowSource property contains the list "Red; Green; Blue; Yellow" and the ColumnCount property is set to 2, the first row of the combo box or list box list will contain "Red" in the first column and "Green" in the second column. The second row will contain "Blue" in the first column and "Yellow" in the second column.

You can use the ColumnWidths property to set the width of the columns displayed in the control, or to hide columns.

See Also

BoundColumn property, Column property, ColumnHeads property, ColumnWidths property, ControlSource property, LimitToList property, RowSourceType, RowSource properties.

Example

See the Column property example.

ColumnHeadings Property

Applies To

Crosstab query.

Description

You can use the ColumnHeadings property to specify the order or to 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.

Setting

Enter the data values from the Column Heading field of the crosstab query as a string expression in the order you want the headings displayed in the datasheet for the crosstab query, separated by a comma (or the list separator set in the Regional Settings Properties dialog box in Windows Control Panel). The following table shows sample ColumnHeadings property 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.

Page 114: Microsoft Access Language

Microsoft Access Language Reference Página 114 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the query's property sheet. You can also set it in SQL view of the Query window or in Visual Basic 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 Heading field in the query design grid. Otherwise, the data won't appear in the columns.

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.

See Also

ColumnHeads property, TRANSFORM statement ("SQL Language Reference").

Example

The following example creates four column headings (Qtr 1, Qtr 2, Qtr 3, Qtr 4) in Datasheet view of a crosstab query listing the quarterly orders by product. You enter the following statement in SQL view of the Query window.

TRANSFORM Sum(CCur([Order Details].UnitPrice * [Order Details].Quantity * (1-[Discount])/100) * 100)AS ProductAmount SELECT Products.ProductName FROM ProductsINNER JOIN (Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID)ON Products.ProductID = [Order Details].ProductIDWHERE (((Orders.ShippedDate) Between #1/1/94# And #12/31/94#))GROUP BY Products.ProductName PIVOT "Qtr " & DatePart("q",[ShippedDate],1,0);

ColumnHeads Property

Applies To

"Mexico", "Canada", "USA"

Displays column headings for each country.

Page 115: Microsoft Access Language

Microsoft Access Language Reference Página 115 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Chart control, Combo Box control, List Box control, Table field, Unbound Object Frame control.

Description

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 control. What is actually displayed as the first-row column heading depends on the object's RowSourceType property setting.

Setting

The ColumnHeads property uses the following settings.

You can set the ColumnHeads property by using the control's property sheet, a macro, or Visual Basic.

For table fields, you can set this property on the Lookup tab of the Field Properties section of table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Tip Microsoft Access sets the ColumnHeads 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 (the ColumnCount property is set to 3) and the RowSourceType property is set to Table/Query, the first three field names (or captions) are used as headings.

If the RowSourceType property is set to Value List, the first row of data items entered in the value list (as the setting of the RowSource property) will be column headings. For example, if a list box has three columns and the RowSourceType property is set to Value List, the first three items in the RowSource property setting are used as column headings.

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 chart labels.

True (–1)

No (Default) Column headings are not enabled.

False (0)

Page 116: Microsoft Access Language

Microsoft Access Language Reference Página 116 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Tip If you can't select the first row of a list box or combo box in Form view, check to see if the ColumnHeads property is set to Yes.

Headings in combo boxes appear only when displaying the list in the control.

See Also

BoundColumn property, ColumnCount property, ColumnHeadings property, ColumnWidths property, ControlSource property, LimitToList property, ListRows property, ListWidth property, RowSourceType, RowSource properties.

ColumnHidden Property

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Field object, List Box control, Option Button control, Option Group control, QueryDef object, Table field, TableDef object, Text Box control, Toggle Button control.

Description

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

You can set the ColumnHidden property by clicking Hide Columns or Unhide Columns on the Format menu in Datasheet view.

You can also set this property by using a Long Integer value in Visual Basic to specify the following settings.

To set or change this property for a table or query by using Visual Basic, you must use a field's Properties collection. For details on using the Properties collection, see Property Object, Properties Collection Summary.

Setting Description

True (–1) The column is hidden.

False (0) (Default) The column is visible.

Page 117: Microsoft Access Language

Microsoft Access Language Reference Página 117 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note The ColumnHidden property is not available in Design view.

Remarks

Hiding a column with the ColumnHidden property in Datasheet view doesn't 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.

See Also

ColumnOrder property, ColumnWidth property, RowHeight 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 dbs As DatabaseSet dbs = CurrentDbShowColumn dbs.TableDefs!Products.Fields!ProductID, False

Sub ShowColumn(fldObject As Field, intShow As Integer) ' Set ColumnHidden property. SetFieldProperty fldObject, "ColumnHidden", dbLong, Not intShowEnd 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 prpProperty 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 prpProperty = fldField.CreateProperty(strPropertyName, _

Page 118: Microsoft Access Language

Microsoft Access Language Reference Página 118 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

intPropertyType, varPropertyValue) fldField.Properties.Append prpProperty End If End IfEnd Sub

ColumnOrder Property

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Field object, List Box control, Option Button control, Option Group control, QueryDef object, Table field, TableDef object, Text Box control, Toggle Button control.

Description

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 can set this property by selecting a column in Datasheet view and dragging it to a new position.

You can also set this property by using a Long Integer value in Visual Basic.

To set or change this property for a table or query by using Visual Basic, you must use a field's Properties collection. For details, see Property Object, Properties Collection Summary.

Note The ColumnOrder property isn't available in 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 property for that field and every field to the left of its original position in Datasheet view.

In other views, the 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 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.

See Also

ColumnHidden property, ColumnWidth property, FrozenColumns property, RowHeight property.

Page 119: Microsoft Access Language

Microsoft Access Language Reference Página 119 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 = 1Forms!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. If this procedure is run while the table is open, changes will not be displayed until is closed and reopened.

Dim dbs As Database, tdfProducts As TableDefSet dbs = CurrentDbSet tdfProducts = dbs!ProductsSetFieldProperty tdfProducts!ProductName, "ColumnOrder", dbLong, 2SetFieldProperty tdfProducts!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 prpProperty 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 prpProperty = fldField.CreateProperty(strPropertyName, _ intPropertyType, varPropertyValue) fldField.Properties.Append prpProperty End If End IfEnd Sub

ColumnWidth Property

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Field object, List Box control, Option Button control, Option Group control, QueryDef object, Table field, TableDef object, Text Box control, Toggle Button control.

Description

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

Page 120: Microsoft Access Language

Microsoft Access Language Reference Página 120 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by dragging the right border of the column selector or by clicking Column Width on the Format menu in Datasheet view and entering the desired value. When you set the ColumnWidth property by using the ColumnWidth command, the value is expressed in points.

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.

Remarks

Setting this property to 0, or resizing the field to a zero width in Datasheet view, sets the field's ColumnHidden property to True (–1) and hides the field in Datasheet view.

Setting a field's ColumnHidden property to False (0) 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 the 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.

See Also

ColumnHidden property, ColumnOrder property, RowHeight property.

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 dbs As Database, tdfCustomers As TableDefSet dbs = CurrentDbSet tdfCustomers = dbs![Customers]SetTableProperty tdfCustomers, "RowHeight", dbLong, 450SetFieldProperty tdfCustomers![Address], "ColumnWidth", dbInteger, 2160

Setting Description

0 Hides the column.

–1 (Default) Sizes the column to the default width.

Page 121: Microsoft Access Language

Microsoft Access Language Reference Página 121 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 = 450Forms![Customers]![Address].ColumnWidth = -2

ColumnWidths Property

Applies To

Combo Box control, List Box control, Table field.

Description

You can use the ColumnWidths property to specify the width of each column in a multiple-column combo box or list box. You can also use this property to hide one or more columns.

Setting

The ColumnWidths property holds a value specifying the width of each column in inches or centimeters, depending on the measurement system (U.S. or Metric) selected in the Measurement System box on the Number tab of the Regional Settings Properties dialog box of Windows Control Panel. The default setting is 1 inch or 2.54 centimeters. The ColumnWidths property setting must be a value from 0 to 22 inches (55.87 cm) for each column in the list box or combo box.

To separate your column entries, use semicolons (;) as list separators (or the list separator selected in the List Separator box on the Number tab of the Regional Settings Properties dialog box).

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 by using the control's property sheet, a macro, or Visual Basic.

For table fields, you can set this property on the Lookup tab of the Field Properties section of table Design view for fields with the DisplayControl property set to Combo Box or List Box.

Tip Microsoft Access sets the ColumnWidths 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 values in twips. Column widths are separated by semicolons. To specify a different unit of measurement, include the unit of measure (cm or in). For example, the following string expression specifies three column widths in centimeters.

Page 122: Microsoft Access Language

Microsoft Access Language Reference Página 122 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

"6 cm;0;6 cm"

Remarks

If you leave the ColumnWidths property setting blank, 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 with three columns.

Note This property is different than the ColumnWidth property, which specifies the width of a specified column in a datasheet.

See Also

BoundColumn property, ColumnCount property, ColumnHeads property, ColumnWidth property, ControlSource property, ListRows property, ListWidth property.

Command Function

Description

You can use the Command function to return the argument portion of the command line used to

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).

Page 123: Microsoft Access Language

Microsoft Access Language Reference Página 123 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 Advanced 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 of the text box to an expression like the following:

=Command()

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 by using the Command function.

To test this example, click the Windows Start button and click Run. Type the following in the Run dialog box, on a single line. (You must surround the parts of the command line information in quotation marks).

"C:\Program Files\Microsoft Office\Office\Msaccess.exe" _ "C:\Program Files\Microsoft Office\Office\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 IfEnd 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.

Page 124: Microsoft Access Language

Microsoft Access Language Reference Página 124 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

CommandBars Property

Applies To

Application object.

Description

You can use the CommandBars property to return a reference to the CommandBars collection object.

Setting

[application.]CommandBars[.method or property]

The CommandBars property uses the following settings.

The CommandBars property is available only by using Visual Basic.

Remarks

The CommandBars collection object is the collection of all built-in and custom command bars in an application. You can refer to individual members of the collection by using the member object's index or a string expression that is the name of the member object. The first member object in the collection has an index value of 1 and the total number of member objects in the collection is the value of the CommandBars collection's Count property.

Once you establish a reference to the CommandBars collection object, you can access all the properties and methods of the object. You can set a reference to the CommandBars collection object by clicking References on the Tools menu while in module Design view. Set a reference to the Microsoft Office 8.0 Object Library in the References dialog box by selecting the appropriate check box.

Setting Description

application Optional. The Application object.

CommandBars Required. When used without specifying a method or property, returns the CommandBars collection object.

method or property

A method or property of the CommandBars collection object. The Item property (collections) is the default property for the CommandBars collection object.

Page 125: Microsoft Access Language

Microsoft Access Language Reference Página 125 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

CommandBars collection object, Count property ("Microsoft Office Language Reference" in Volume 5), Item property (collections).

Example

The following example uses the CommandBars property of the Application object to manipulate various properties and methods of the CommandBars collection object. To try this example, paste the following code into the Declarations section of a standard module. Create a reference to the Microsoft Office 8.0 Object Library by using the References dialog box, available by clicking References on the Tools menu. Then click anywhere inside the GetCommandBarInfo procedure and press F5 to run it.

Sub GetCommandBarInfo() Dim strCBBarName As String

strCBBarName = InputBox("Enter the name of a command bar", _ "Get CommandBar Information", "Menu Bar") If Len(strCBBarName) > 0 Then CommandBarInfo strCBBarName End IfEnd Sub

Sub CommandBarInfo(strCBBarName As String) Dim cbr As CommandBar

On Error Resume Next Set cbr = CommandBars(strCBBarName) If Err = 0 then With cbr MsgBox "The command bar named '" & .Name & "' contains " & _ .Controls.Count & IIf(.Controls.Count = 1, " control and ", _ " controls and ") & IIf(.BuiltIn, "is", "is not") & _ " a built-in toolbar", vbOKOnly, "'" & _ .Name & "' Information:" End With Else MsgBox "Invalid CommandBar Name" End IfEnd Sub

Control Object

Description

The Control object represents a control on a form, report, or section, within another control, or attached to another control. The following diagram shows the Control object in relation to a Form or Report object.

Remarks

All controls on a form or report belong to the Controls collection for that Form or Report object. Controls within a particular section belong to the Controls collection for that section. Controls within a tab control or option group control belong to the Controls collection for that control. A label control that is attached to another control belongs to the Controls collection for that control.

Page 126: Microsoft Access Language

Microsoft Access Language Reference Página 126 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

When you refer to an individual Control object in the Controls collection, you can refer to the Controls collection either implicitly or explicitly.

' Implicitly refer to NewData control in Controls collection.Me!NewData

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

' Performance slightly slower.Me("NewData")

' Refer to a control by its index in the controls collection.Me(0)

' Refer to a NewData control by using the subform Controls collection.Me.ctlSubForm.Controls!NewData

' Explicitly refer to the NewData control in the Controls collection.Me.Controls!NewData

Me.Controls("NewData")

Me.Controls(0)

Note You can use the Me keyword to represent a Form or Report object within code only if you're referring to the form or report from code within the class module. If you're referring to a form or report from a standard module or a different form's 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. The constants for the various Microsoft Access controls are set forth in the control's ControlType property.

To determine the type of an existing control, you can 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.

If you do know the data type of the control to which you are referring, and the control is a built-in Microsoft Access control, you should represent it with a variable of a specific type. For example, if you know that a particular control is a text box, declare a variable of type TextBox to represent it, as shown in the following code.

Dim txt As TextBoxSet txt = Forms!Employees!LastName

Note If a control is an ActiveX control, then you must declare a variable of type Control to represent it; you cannot use a specific type. If you're not certain what type of control a variable will point to, declare the variable as type Control.

The option group control can contain other controls within its Controls collection, including option button, check box, toggle button, and label controls.

The tab control contains a Pages collection, which is a special type of Controls collection. The Pages collection contains Page objects, which are controls. Each Page object in turn contains a

Page 127: Microsoft Access Language

Microsoft Access Language Reference Página 127 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Controls collection, which contains all of the controls on that page.

Other Control objects have a Controls collection that can contain an attached label. These controls include the text box, option group, option button, toggle button, check box, combo box, list box, command button, bound object frame, and unbound object frame controls.

Properties

Application property, Column property, Form, Report properties, Hyperlink property, ItemData property, Object property, ObjectVerbs property, OldValue property, Page, Pages properties, Parent property, Selected property.

Methods

Dropdown method, Requery method (Control or Form object), SetFocus method, SizeToFit method, Undo method.

See Also

Controls collection, CreateControl, CreateReportControl functions, Form object, Report object.

Example

The following example enumerates all the controls in the Controls collection of a form. The procedure is called from a form module and the Me keyword is used to pass the Form object to the procedure. The procedure sets certain properties if the control is a text box.

' Call SetTextBoxProperties procedure.SetTextBoxProperties Me

Sub SetTextBoxProperties(frm As Form) Dim ctl As Control

' 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 ctlEnd Sub

ControlBox Property

Applies To

Form.

Description

Page 128: Microsoft Access Language

Microsoft Access Language Reference Página 128 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the ControlBox property to specify whether a form has a Control menu in Form view and Datasheet view.

Setting

The ControlBox property uses the following settings.

Note Setting the ControlBox property to No also removes the Minimize, Maximize, and Close buttons on a form.

You can set this property by using the form's property sheet, a macro, or Visual Basic.

You can set this property only in form Design view.

Remarks

To display a Control menu on a form, the ControlBox property must be set to 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:

l Open the form in Form view from the Database window.l Open the form from a macro.l Open the form from Visual Basic.l Open the form in Datasheet view.l Switch to Form view or Datasheet view from Design view.

See Also

BorderStyle property, CloseButton property, MinMaxButtons property, Modal property, PopUp property.

Example

The following example sets the ControlBox property on the WarningDialog form to False (0):

Setting Description Visual Basic

Yes (Default) The form has a Control menu in Form view and Datasheet view.

True (–1)

No The form doesn't have a Control menu in Form view and Datasheet view.

False (0)

Page 129: Microsoft Access Language

Microsoft Access Language Reference Página 129 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Forms!WarningDialog.ControlBox = False

Controls Collection

Description

The Controls collection contains all of the controls on a form, report, or section, within another control, or attached to another control. The Controls collection is a member of a Form, Report, Section, or Control object. The following diagram illustrates the relationship between the Controls collection and 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 is 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's or report's module, you must use the full reference to the form or report.

To work with the controls on a section of a form or report, use the Section property to return a reference to a Section object. Then refer to the Controls collection of the Section object.

Page 130: Microsoft Access Language

Microsoft Access Language Reference Página 130 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Two types of Control objects, the tab control and option group control, have Controls collections that can contain multiple controls. The Controls collection belonging to the option group control contains any option button, check box, toggle button, or label controls in the option group.

The tab control contains a Pages collection, which is a special type of Controls collection. The Pages collection contains Page objects. Page objects are also controls. The ControlType property constant for a Page control is acPage. A Page object, in turn, has its own Controls collection, which contains all the controls on an individual page.

Other Control objects have a Controls collection that can contain an attached label. These controls include the text box, option group, option button, toggle button, check box, combo box, list box, command button, bound object frame, and unbound object frame controls.

Properties

Application property, Count property, Item property (ObjectFrame control), Parent property.

See Also

Control object, For Each...Next statement, Form object, Report object.

Example

See the Control object example.

ControlSource Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, List Box control, Option Button control, Option Group control, Text Box control, Toggle Button control.

Description

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 uses the following settings.

Page 131: Microsoft Access Language

Microsoft Access Language Reference Página 131 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the ControlSource property for a control by 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 Design view 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, you can use 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.) If you click a control bound to a field that has a Hyperlink data type, you jump to the destination specified in the hyperlink address.

An expression

The control displays data generated by an expression. This data can be changed by the user but isn't saved in the database.

Sample setting Description

LastName 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.

Page 132: Microsoft Access Language

Microsoft Access Language Reference Página 132 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

Load, Unload events, RecordSource property, RowSourceType, RowSource properties.

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.

Me!Expected.ControlSource = "=Date() + 7"

ControlTipText Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Image control, Label control, List Box control, Option Button control, Option Group control, Page, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

You can use the ControlTipText property to specify the text that appears in a ScreenTip when you hold the mouse pointer over a control.

Setting

You set the ControlTipText property by using a string expression up to 255 characters long.

You can set the ControlTipText property by using the control's property sheet, a macro, or Visual Basic.

=Date( ) + 7 For a control, this expression displays a date seven days from today in the control.

=DatePart("q",ShippedDate)

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.

Page 133: Microsoft Access Language

Microsoft Access Language Reference Página 133 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

For controls on forms, you can set the default for this property by using the default control style or the DefaultControl method in 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 information about 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.

See Also

HelpContextID, HelpFile properties, StatusBarText property, WhatsThisButton property.

ControlType Property

Applies To

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

Description

You can use the ControlType property in Visual Basic to determine the type of a control on a form or report.

Setting

The ControlType property setting is an intrinsic constant that specifies the control type.

Constant Control

acLabel Label

acRectangle Rectangle

Page 134: Microsoft Access Language

Microsoft Access Language Reference Página 134 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

acLine Line

acImage Image

acCommandButton Command button

acOptionButton Option button

acCheckBox Check box

acOptionGroup Option group

acBoundObjectFrame Bound object frame

acTextBox Text box

acListBox List box

acComboBox Combo box

acSubform Subform/subreport

acObjectFrame Unbound object frame or chart

acPageBreak Page break

acPage Page

acCustomControl ActiveX (custom) control

acToggleButton Toggle button

acTabCtl Tab

Page 135: Microsoft Access Language

Microsoft Access Language Reference Página 135 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The ControlType property can only be set by using Visual Basic in form Design view or report Design view, but it 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 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 doesn't affect whether data can be edited; it's used here to provide a visual cue that the control behavior has changed.)

The ControlType property is also used to specify the type of control to create when you are using the CreateControl function.

See Also

CreateControl, CreateReportControl functions.

Example

See the AllowAdditions property example.

CopyObject Action

Description

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 back up an existing object in another database or quickly create a similar object with a few changes.

Setting

The CopyObject action has the following arguments.

Action argument

Description

Page 136: Microsoft Access Language

Microsoft Access Language Reference Página 136 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Remarks

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

Destination Database

A valid path and file name for the destination database. Enter the path and file name in the Destination Database box in the Action Arguments section of the Macro window. 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. To copy the object selected in the Database window, leave this argument 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 Name box, click the object to copy. If you leave the Source Object Type argument blank, leave this argument 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.

Page 137: Microsoft Access Language

Microsoft Access Language Reference Página 137 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 file name 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.

See Also

CopyObject method, Rename action, Save action, TransferDatabase action.

CopyObject Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Page 138: Microsoft Access Language

Microsoft Access Language Reference Página 138 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Argument Description

destinationdatabase A string expression that's 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's 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:

acDefault (default)acFormacMacroacModuleacQueryacReportacTable

sourceobjectname A string expression that's the valid name of an object of the type selected by the sourceobjecttype argument.

If you run 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.

Page 139: Microsoft Access Language

Microsoft Access Language Reference Página 139 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

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

If you leave the sourceobjecttype and sourceobjectname arguments blank (the default constant, acDefault, is assumed for sourceobjecttype), 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.

See Also

CopyObject action, DoCmd object, Rename method, SelectObject method, TransferDatabase method.

Example

The following 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"

Count Property

Applies To

Controls collection, Forms collection, Modules collection, Pages collection, References collection, Reports collection.

Description

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 value and is read-only in all views.

You can determine the Count property for an object by using a macro or Visual Basic.

If no forms or reports are open, the Count property setting is 0.

See Also

Count property ("DAO Language Reference"), Count property ("Microsoft Visual Basic for

Page 140: Microsoft Access Language

Microsoft Access Language Reference Página 140 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applications Language Reference" in Volume 5).

Example

The following example uses the Count property to control a loop that prints information about all open forms and their controls.

Sub Print_Form_Controls() Dim frm As Form, intI As Integer Dim intJ As Integer Dim intControls As Integer, intForms As Integer 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 intControls = frm.Count If intControls > 0 Then For intJ = 0 To intControls - 1 Debug.Print vbTab; frm(intJ).Name Next intJ Else Debug.Print vbTab; "(no controls)" End If Next intI Else MsgBox "No open forms.", vbExclamation, "Form Controls" End IfEnd Sub

The next example determines the number of controls on a form and a report and assigns the number to a variable.

Dim intFormControls As IntegerDim intReportControls As IntegerintFormControls = Forms!Employees.CountintReportControls = Reports!FreightCharges.Count

CountOfDeclarationLines Property

Applies To

Module object.

Description

The CountOfDeclarationLines property returns a Long value indicating the number of lines of code in the Declarations section in a standard module or class module.

Setting

The CountOfDeclarationLines property is available only by using Visual Basic and is read-only.

Remarks

Lines in a module are numbered beginning with 1.

Page 141: Microsoft Access Language

Microsoft Access Language Reference Página 141 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The value of the CountOfDeclarationLines property is equal to the line number of the last line of the Declarations section. You can use this property to determine where the Declarations section ends and the body of the module begins.

See Also

CountOfLines property.

Example

The following example counts the number of lines and declaration lines in each standard module in the Modules collection. Note that the Modules collection contains only modules that are open in the module editor.

Function ModuleLineTotal(strModuleName As String) Dim mdl As Module

' Open module to include in Modules collection. DoCmd.OpenModule strModuleName ' Return reference to Module object. Set mdl = Modules(strModuleName) ' Print number of lines in module. Debug.Print "Number of lines: ", mdl.CountOfLines ' Print number of declaration lines. Debug.Print "Number of declaration lines: ", _ mdl.CountOfDeclarationLinesEnd Function

CountOfLines Property

Applies To

Module object.

Description

The CountOfLines property returns a Long value indicating the number of lines of code in a standard module or class module.

Setting

The CountOfLines property is available only by using Visual Basic and is read-only.

Remarks

Lines in a module are numbered beginning with 1.

The line number of the last line in a module is the value of the CountOfLines property.

See Also

CountOfDeclarationLines property.

Page 142: Microsoft Access Language

Microsoft Access Language Reference Página 142 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

See the CountOfDeclarationLines property example.

CreateControl, CreateReportControl Functions

Description

l The CreateControl function creates a control on a specified open form.l The CreateReportControl function creates 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 have 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. To view these constants and paste them into your code from the Object Browser, click the Object Browser button on the Visual Basic toolbar, then click Access in

Page 143: Microsoft Access Language

Microsoft Access Language Reference Página 143 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

then click Access in the Project/Library box, and click Constants in the Classes box.

Constant Control

acLabel Label

acRectangle Rectangle

acLine Line

acImage Image

acCommandButton Command button

acOptionButton Option button

acCheckBox Check box

acOptionGroup Option group

acBoundObjectFrame Bound object frame

acTextBox Text box

acListBox List box

acComboBox Combo box

Page 144: Microsoft Access Language

Microsoft Access Language Reference Página 144 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

acSubform Subform

acObjectFrame Unbound object frame

acPage Page

acPageBreak Page break

acCustomControl ActiveX control

acToggleButton Toggle button

acTabCtl Tab control

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

Page 145: Microsoft Access Language

Microsoft Access Language Reference Página 145 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Page 146: Microsoft Access Language

Microsoft Access Language Reference Página 146 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can 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

parent A 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, or omit it.

columnname The 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 won't 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.

Page 147: Microsoft Access Language

Microsoft Access Language Reference Página 147 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Note 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.

See Also

CreateForm, CreateReport functions, DeleteControl, DeleteReportControl statements, Section property.

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.RestoreEnd Sub

CreateEventProc Method

Page 148: Microsoft Access Language

Microsoft Access Language Reference Página 148 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Module object.

Description

The CreateEventProc method creates an event procedure in a class module. It returns a Long value that indicates the line number of the first line of the event procedure.

Syntax

object.CreateEventProc(eventname, objectname)

The CreateEventProc method has the following arguments.

Remarks

The CreateEventProc method creates a code stub for an event procedure for the specified object. For example, you can use this method to create a Click event procedure for a command button on a form. Microsoft Access creates the Click event procedure in the module associated with the form that contains the command button.

Once you've created the event procedure code stub by using the CreateEventProc method, you can add lines of code to the procedure by using other methods of the Module object. For example, you can use the InsertLines method to insert a line of code.

Example

The following example creates a new form, adds a command button, and creates a Click event procedure for the command button:

Argument Description

object A Module object whose Type property returns acClassModule, a constant with a value of 1.

eventname A string expression that evaluates to the name of an event.

objectname An object that has the event specified by the eventname argument. It may be a Form, Report, or Control object, a form or report section, or a class module.

Page 149: Microsoft Access Language

Microsoft Access Language Reference Página 149 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Function ClickEventProc() As Boolean Dim frm As Form, ctl As Control, mdl As Module Dim lngReturn As Long

On Error GoTo Error_ClickEventProc ' Create new form. Set frm = CreateForm ' Create command button on form. Set ctl = CreateControl(frm.Name, acCommandButton, , , , 1000, 1000) ctl.Caption = "Click here" ' Return reference to form module. Set mdl = frm.Module ' Add event procedure. lngReturn = mdl.CreateEventProc("Click", ctl.Name) ' Insert text into body of procedure. mdl.InsertLines lngReturn + 1, vbTab & "MsgBox ""Way cool!""" ClickEventProc = True

Exit_ClickEventProc: Exit Function

Error_ClickEventProc: MsgBox Err & " :" & Err.Description ClickEventProc = False Resume Exit_ClickEventProcEnd Function

CreateForm, CreateReport Functions

Description

l The CreateForm function creates a form and returns a Form object.l 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 have the following arguments.

Argument Description

Page 150: Microsoft Access Language

Microsoft Access Language Reference Página 150 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can 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. Note that if the database specified by the database argument is not the current database, that database must be open as a library database. For more information on library databases, see Chapter 12, "Using Library Databases and Dynamic-Link Libraries," in Building Applications with Microsoft Access 97.

Note If you have created a form or report template in another database that you would like to use as a template, you can simply import it into the current database, rather than loading a library database. Then check to make sure that the proper form or report name is listed in the Form Template or Report Template box on the Forms/Reports tab of the Options dialog box. Forms and reports subsequently created with the CreateForm or CreateReport function will be based on this template.

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 on the Forms/Reports tab of the Options dialog box.

When you create a form or report with the CreateForm or CreateReport function, the form's or report's HasModule property is set to False (0). You can set this property to True (–1) if you want the new form or report to have a class module.

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. If you specify a database other than the current database, that database must be open as a library database.

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. 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.

Page 151: Microsoft Access Language

Microsoft Access Language Reference Página 151 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The CreateForm and CreateReport functions create minimized forms and reports.

See Also

CreateControl, CreateReportControl functions.

Example

The following example creates a report in the current database by using the template specified by the Report Template setting on 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( , "Customers") DoCmd.Restore ' Set RecordSource property to Customers table. frm.RecordSource = "Customers"End Sub

CreateGroupLevel Function

Description

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 has the following arguments.

Page 152: Microsoft Access Language

Microsoft Access Language Reference Página 152 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can use the CreateGroupLevel function when designing a wizard that creates a report with groups or totals. The CreateGroupLevel function groups or sorts data on the specified field or expression and creates 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. The CreateGroupLevel function adds a new group level to the array, based on the expression argument. The CreateGroupLevel function 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 the 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 in the report's Sorting And Grouping box, available by clicking the Sorting And Grouping button on the Report Design toolbar.

Note If your wizard creates group levels in a new or existing report, it must open the report in Design view.

See Also

GroupHeader, GroupFooter properties, GroupInterval property, GroupLevel property, GroupOn

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 group footer. If the header or footer argument is True (–1), the field or expression will have a group header or footer. If the header or footer argument is False (0), the field or expression won't. You can create both a header and a footer by setting both arguments to True.

Page 153: Microsoft Access Language

Microsoft Access Language Reference Página 153 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

property, KeepTogether property — groups, SortOrder property.

Example

The following example 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 (–1), 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 = 400End Sub

CreateReport Function

See CreateForm, CreateReport Functions.

CreateReportControl Function

See CreateControl, CreateReportControl Functions.

Current Event

Applies To

Form.

Description

The Current event occurs when the focus moves to a record, making it the current record, or when the form is refreshed or requeried.

Remarks

To run a macro or event procedure when this event occurs, set the OnCurrent property to the name of the macro or to [Event Procedure].

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.

Page 154: Microsoft Access Language

Microsoft Access Language Reference Página 154 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

By running a macro or 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 runs a GoToControl or GoToRecord action or the corresponding method of the DoCmd object 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 — for example, when you click Remove Filter/Sort on 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

See Also

Activate, Deactivate events, Event properties, GotFocus, LostFocus events, GoToRecord action, Load, Unload events, Open, Close events.

Current Event — Event Procedures

Description

To create an event procedure that runs 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 by 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.

See Also

Current event — macros.

Example

In the following example, a Current event procedure checks the status of an option button called Discontinued. If the button is selected, the example sets the background color of the ProductName field to red to indicate that the product has been discontinued.

Page 155: Microsoft Access Language

Microsoft Access Language Reference Página 155 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To try the example, add the following event procedure to a form that contains an option called Discontinued and a text box called ProductName.

Private Sub Form_Current() If Me!Discontinued Then Me!ProductName.BackColor = 255 EndIfEnd Sub

The next 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.

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

Private Sub Form_Current() Me.Caption = Me!SupplierNameEnd Sub

Current Event — Macros

Description

To run a macro when the Current event occurs, set the OnCurrent property to the name of the macro.

Remarks

You can't use the CancelEvent action in a Current macro to cancel the Current event. However, you can use the GoToRecord action to move the focus to a different record.

See Also

Current event — event procedures.

CurrentDb Function

Description

The CurrentDb function returns an object variable of type Database that represents the database currently open in the Microsoft Access window.

Syntax

CurrentDb

Remarks

Page 156: Microsoft Access Language

Microsoft Access Language Reference Página 156 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

In order to manipulate the structure of your database and its data from Visual Basic, you must use Data Access Objects (DAO). 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 DAO 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 DatabaseSet dbsA = CurrentDbSet 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 97, 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. The CurrentDb function enables you to create more than one variable of type Database that refers 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 DatabaseSet dbsCurrent = CurrentDbSet dbsContacts = DBEngine.Workspaces(0).OpenDatabase("Contacts.mdb")

See Also

Database object ("DAO Language Reference"), Databases collection ("DAO Language Reference").

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 fldEnd Sub

Page 157: Microsoft Access Language

Microsoft Access Language Reference Página 157 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

CurrentObjectType, CurrentObjectName Properties

Applies To

Application object.

Description

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. The active database object is the object that has the focus or in which code is running.

Setting

The CurrentObjectType property is set by Microsoft Access to one of the following Microsoft Access intrinsic constants.

The CurrentObjectName property is set by Microsoft Access to a string expression containing the name of the active object.

These properties are available only by using Visual Basic and are read-only in all views.

Remarks

The following conditions determine which object is considered the active object:

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.

Page 158: Microsoft Access Language

Microsoft Access Language Reference Página 158 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l If the active object is a property sheet, command bar, menu, palette, or field list of an object, the CurrentObjectType and CurrentObjectName properties return the type and name of the underlying object.

l If the active object is a pop-up form, the CurrentObjectType and CurrentObjectName properties refer to the pop-up form itself, not the form from which it was opened.

l If the active object is the Database window, the CurrentObjectType and CurrentObjectName properties return the item selected in the Database window.

l If no object is selected, the CurrentObjectType property returns True (–1), and the CurrentObjectName property returns a zero-length string (" ").

l If the current state is ambiguous (the active object isn't a table, query, form, report, macro, or module) — for example, if a dialog box has the focus — 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).

See Also

SysCmd function.

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, acSaveYes End If End IfEnd Sub

CurrentRecord Property

Applies To

Form.

Description

Page 159: Microsoft Access Language

Microsoft Access Language Reference Página 159 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can 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's not available in Design view. This property is available only by using a macro or 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.

See Also

NewRecord 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 lngrecordnum.

Sub CurrentFormRecord(frm As Form) Dim lngrecordnum As Long

lngrecordnum = frm.CurrentRecordEnd Sub

CurrentSectionLeft, CurrentSectionTop Properties

Applies To

Form.

Description

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.

Page 160: Microsoft Access Language

Microsoft Access Language Reference Página 160 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

l The CurrentSectionLeft property. An Integer value that represents the distance from the left edge of the current section to the left edge of the form.

l The CurrentSectionTop property. An Integer value that represents the distance from the top edge of the current section to the top edge of the form.

These property settings are read-only and are available only by using a macro or Visual Basic.

Remarks

The CurrentSectionLeft and CurrentSectionTop property settings change whenever a user scrolls through a form.

For forms whose DefaultView property is set to Single Form, 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.

For forms whose DefaultView property is set to Continuous Forms, if a section isn't visible, the CurrentSectionTop property is equal to the InsideHeight property of the form.

The CurrentSectionLeft and CurrentSectionTop properties are useful for finding the positions of detail sections displayed in Form view as continuous forms or in Datasheet view. Each detail section has a different CurrentSectionTop property setting, depending on the section's position on the form.

See Also

InsideHeight, InsideWidth properties, Left, Top properties, WindowHeight, WindowWidth 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 & " , " & intCurTopEnd Sub

Page 161: Microsoft Access Language

Microsoft Access Language Reference Página 161 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

CurrentUser Function

Description

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. For user accounts other than Admin, you can 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)

CurrentView Property

Applies To

Form, Form object.

Description

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 by using Visual Basic.

Settings

The CurrentView property uses the following settings.

Page 162: Microsoft Access Language

Microsoft Access Language Reference Página 162 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property is available only by using 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 current view. For example, an event procedure could 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.

See Also

DefaultView, ViewsAllowed properties.

Example

The following example uses the GetCurrentView subroutine to determine whether a form is in Form or Datasheet view. If it's in Form view, a message to the user is displayed in a text box on the form; if it's in Datasheet view, the same message is displayed in a message box.

GetCurrentView Me, "Please contact system administrator."

Sub 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 ' Display message in text box. frm!MessageTextBox = strDisplayMsg Case conDataSheet ' Display message in message box. MsgBox strDisplayMsg End SelectEnd Sub

CurrentX, CurrentY Properties

Applies To

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.

Page 163: Microsoft Access Language

Microsoft Access Language Reference Página 163 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Report.

Description

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 can use these properties to determine where the center point of a circle is drawn on a report section.

Setting

l The CurrentX property specifies a Single value used in a numeric expression to set the horizontal coordinate of the next printing drawing method.

l The CurrentY property specifies a Single 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 by using 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.

See Also

Circle method, DrawMode property, DrawStyle property, Event properties, Left, Top properties, Line method, Print event, Print method, Scale method, ScaleHeight, ScaleWidth properties, ScaleLeft, ScaleTop properties, ScaleMode property.

Method Sets CurrentX, CurrentY properties to

Circle The center of the object.

Line The end point of the line (the x2, y2 coordinates).

Print The next print position.

Page 164: Microsoft Access Language

Microsoft Access Language Reference Página 164 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

See the Print method example.

Cycle Property

Applies To

Form.

Description

You can use the Cycle property to specify what happens when you press the TAB key and the focus is in the last control on a bound form.

Setting

The Cycle property uses the following settings.

You can set the Cycle property by using the form's property sheet, a macro, or 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 each 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

Setting Description Visual Basic

All Records (Default) Pressing the TAB key from the last control on a form moves the focus to the first control in the tab order in the next record.

0

Current Record

Pressing the TAB key from the last control on a record moves the focus to the first control in the tab order 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

Page 165: Microsoft Access Language

Microsoft Access Language Reference Página 165 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

user to move to a new record by pressing the TAB key.

Note The Cycle property only controls the TAB key behavior on the form where the property is set. If a subform control is in the tab order, once the subform control receives the focus, the Cycle property setting for the subform determines what happens when you press the TAB key.

To move the focus outside a subform control, press CTRL+TAB.

See Also

TabIndex property, TabStop property.

Database Properties

Applies To

Database object.

Description

The Database properties allow you to provide additional information about your database. To view the Database properties, click Database Properties on the File menu.

Setting

You can set these properties by entering information in the Summary or Custom tabs in the DatabaseName Properties dialog box or by using Visual Basic.

In Visual Basic, if a Database property hasn't already been set in the DatabaseName Properties dialog box, you must create the property by using the CreateProperty method and append it to the Properties collection of a Document object. With Visual Basic, you can set the properties that appear on the Summary tab by using the SummaryInfo Document object in the Documents collection. You set properties in the Custom tab by using the UserDefined Document object in the Documents collection. You must supply a name, data type, and default value for a custom Database property before you can add it to your database. For more information, the Documents collection specifics (Microsoft Access) in the "DAO Language Reference" part.

Note You can only enter or edit the properties that appear on the Summary or Custom tabs. The other Database properties are read-only.

Remarks

The Database properties appear in the DatabaseName Properties dialog box on the following tabs.

Page 166: Microsoft Access Language

Microsoft Access Language Reference Página 166 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

See Also

Tab Description

General This is the same information that is displayed when you right-click the name of a file in Windows Explorer and then click Properties on the shortcut menu. The only difference is that when these properties are viewed in Microsoft Access, the Attributes settings are read-only.

Summary The information you enter on this tab is added to the SummaryInfo Document object 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 from other programs such as the Windows Find Files program.

The Hyperlink Base setting on the Summary tab is used to create the base hyperlink path that is appended to the beginning of relative HyperlinkAddress property settings.

Statistics This information includes the date and time the active database was created, and the last date and time it was modified, accessed, and printed.

Contents This information includes the names of the objects contained in your database.

Custom The custom properties you enter become properties of the UserDefined Document object in the Documents collection.

Page 167: Microsoft Access Language

Microsoft Access Language Reference Página 167 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Append method ("DAO Language Reference"), Containers collection ("DAO Language Reference"), CreateProperty method ("DAO Language Reference"), Document object ("DAO Language Reference"), Documents collection ("DAO Language Reference"), Properties collection ("DAO Language Reference").

Example

In the following example, you can set or create a custom user-defined property that will appear on the Custom tab of the DatabaseName Properties dialog box. For example, you could call the SetCustomProperty function to add a new property called LastUserName to the UserDefined Document object 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 ' Error occurred trying to set property. MsgBox "Error occurred 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 error occurs here it means ' property doesn't exist and needs to be created and appended ' to Properties collection of Document object. Set prp = doc.Properties(strPropName) prp = strPropValue ' Set custom property value. SetCustomProperty = TrueSetCustom_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 IfEnd Function

The next example demonstrates how to display information from the Summary tab of the DatabaseName Properties dialog box. The application's title, subject, and author are displayed in text box controls on a form. In this example, if the property hasn't already been set, "None" is returned from the procedure. If an unknown error occurs, 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"

Page 168: Microsoft Access Language

Microsoft Access Language Reference Página 168 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

' Property not found error. Const conPropertyNotFound = 3270 On Error GoTo GetSummary_Err Set dbs = CurrentDb Set cnt = dbs.Containers!Databases Set doc = cnt.Documents!SummaryInfo doc.Properties.Refresh GetSummaryInfo = doc.Properties(strPropName)

GetSummary_Bye: Exit Function

GetSummary_Err: If Err = conPropertyNotFound Then Set prp = doc.CreateProperty(strPropName, dbText, "None") ' Append to collection. doc.Properties.Append prp Resume Else ' Unknown error. GetSummaryInfo = "" Resume GetSummary_Bye End IfEnd Function

DataEntry Property

Applies To

Form.

Description

You can use the DataEntry property to specify whether a bound form opens to allow data entry only. The Data Entry property doesn't determine whether records can be added; it only determines whether existing records are displayed.

Setting

The DataEntry property uses the following settings.

Setting Description Visual Basic

Yes The form opens showing only a blank record. True (–1)

Page 169: Microsoft Access Language

Microsoft Access Language Reference Página 169 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the DataEntry property by using a form's property sheet, a macro, or Visual Basic.

This property can be set in any view.

Remarks

The DataEntry property has an effect only when the AllowAdditions property is set to Yes.

Setting the DataEntry property to Yes by using Visual Basic has the same effect as clicking Data Entry on the Records menu. Setting it to No by using Visual Basic is equivalent to clicking Remove Filter/Sort on the Records menu.

Note When the Data Mode argument of the OpenForm action is set, Microsoft Access will override a number of form property settings. If the Data Mode argument of the OpenForm action is set to Edit, Microsoft Access will open the form with the following property settings:

l AllowEdits — Yesl AllowDeletions — Yesl AllowAdditions — Yesl DataEntry — No

To prevent the OpenForm action from overriding any of these existing property settings, omit the Data Mode argument setting so that Microsoft Access will use the property settings defined by the form.

See Also

AllowAdditions property, AllowDeletions property, AllowEdits property, Enabled, Locked properties, OpenForm action, OpenForm method, RecordsetType property.

DatasheetBackColor, DatasheetForeColor Properties

Applies To

Form object, QueryDef object, TableDef object.

Description

l You can use the DatasheetBackColor property in Visual Basic to specify or determine the background color of an entire table, query, or form in Datasheet view.

l You can use the DatasheetForeColor property in Visual Basic to specify or determine the color of all text in a table, query, or form in Datasheet view.

No (Default) The form opens showing existing records.

False (0)

Page 170: Microsoft Access Language

Microsoft Access Language Reference Página 170 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The DatasheetBackColor and DatasheetForeColor properties are a Long Integer value representing the background color and font color setting for a datasheet.

You can also set these properties by clicking the Fill/BackColor button or the Font/ForeColor button on the Formatting (Datasheet) toolbar and clicking the desired color displayed on the color palette.

You can also set the default DatasheetBackColor and DatasheetForeColor properties by using the Datasheet tab of the Options dialog box, available by clicking Options on the Tools menu.

Remarks

Setting the DatasheetBackColor or DatasheetForeColor properties for a table or query won't affect these property settings for a form that uses the table or query as its source of data.

The following list contains the properties that don't exist in the Properties collection for TableDef or QueryDef objects until you add them by using the CreateProperty method or set them by using the Formatting (Datasheet) toolbar.

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds it to the Properties collection.

See Also

BackColor property, DatasheetCellsEffect property, DatasheetFontItalic, DatasheetFontUnderline properties, DatasheetFontName, DatasheetFontHeight properties, DatasheetFontWeight property, DatasheetGridlinesBehavior property, DatasheetGridlinesColor property, ForeColor property.

Example

The following example uses the SetTableProperty procedure to set a table's font color to dark blue and its background color to light gray. If a "Property not found" error occurs when the

l DatasheetBackColor l DatasheetCellsEffect

l DatasheetFontHeight* l DatasheetFontItalic*

l DatasheetFontName* l DatasheetFontUnderline*

l DatasheetFontWeight * l DatasheetForeColor*

l DatasheetGridlinesBehavior l DatasheetGridlinesColor

Page 171: Microsoft Access Language

Microsoft Access Language Reference Página 171 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

property is set, the CreateProperty method is used to add the property to the object's Properties collection.

Dim dbs As Database, tdfProducts As TableDefConst lngForeColor As Long = 8388608 ' Dark blue.Const lngBackColor As Long = 12632256 ' Light gray.

Set dbs = CurrentDbSet tdfProducts = dbs!ProductsSetTableProperty tdfProducts, "DatasheetBackColor", dbLong, lngBackColorSetTableProperty tdfProducts, "DatasheetForeColor", dbLong, lngForeColor

Sub SetTableProperty(tdfTableObj As TableDef, strPropertyName As String, _ intPropertyType As Integer, varPropertyValue As Variant) Const conErrPropertyNotFound = 3270 Dim prpProperty As Property On Error Resume Next ' Don't trap errors. tdfTableObj.Properties(strPropertyName) = varPropertyValue If Err <> 0 Then ' Error occurred when value set. If Err <> conErrPropertyNotFound Then ' Error is unknown. MsgBox "Couldn't set property '" & strPropertyName _ & "' on table '" & tdfTableObj.Name & "'", vbExclamation, _ Err.Description Err.Clear Else ' Error is "Property not found", so add it to collection. Set prpProperty = tdfTableObj.CreateProperty(strPropertyName, _ intPropertyType, varPropertyValue) tdfTableObj.Properties.Append prpProperty Err.Clear End If End If tdfTableObj.Properties.RefreshEnd Sub

DatasheetCellsEffect Property

Applies To

Form object, QueryDef object, TableDef object.

Description

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.

Page 172: Microsoft Access Language

Microsoft Access Language Reference Página 172 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using Special Effect button on the Formatting (Datasheet) toolbar, by using a macro, or by using Visual Basic.

You can also set this property by selecting the type of cell effect under Cell Effect in the Cells Effects dialog box, available by clicking Cells on the Format menu.

You can set the default DatasheetCellsEffect property by using the settings under Default Cell Effect on the Datasheet tab of the Options dialog box, available by clicking Options on the Tools menu.

Remarks

This property applies the selected effect to the entire datasheet.

When this property is set to Raised or Sunken, gridlines will be visible on the datasheet regardless of the DatasheetGridlinesBehavior property setting.

The following table contains the properties that do not exist in the Properties collection for TableDef or QueryDef objects until you add them using the CreateProperty method or set them using the Formatting (Datasheet) toolbar.

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

l DatasheetBackColor l DatasheetCellsEffect

l DatasheetFontHeight* DatasheetFontItalic*

l DatasheetFontName* l DatasheetFontUnderline*

Page 173: Microsoft Access Language

Microsoft Access Language Reference Página 173 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds all the properties listed with an asterisk to the Properties collection.

See Also

BackColor property, DatasheetBackColor, DatasheetForeColor properties, DatasheetFontItalic, DatasheetFontUnderline properties, DatasheetFontName, DatasheetFontHeight properties, DatasheetFontWeight property, DatasheetGridlinesBehavior property, DatasheetGridlinesColor property, ForeColor property.

DatasheetFontHeight Property

See DatasheetFontName, DatasheetFontHeight Properties.

DatasheetFontItalic, DatasheetFontUnderline Properties

Applies To

Form object, QueryDef object, TableDef object.

Description

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 button or the Underline button on the Formatting (Datasheet) toolbar.

You can also set these properties in the Font dialog box, available by clicking Font on the Format menu in Datasheet view.

In Visual Basic, the DatasheetFontItalic property uses the following settings.

l DatasheetFontWeight* l DatasheetForeColor*

l DatasheetGridlinesBehavior l DatasheetGridlinesColor

Page 174: Microsoft Access Language

Microsoft Access Language Reference Página 174 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

In Visual Basic, the DatasheetFontUnderline property uses the following settings.

In Visual Basic, these property settings are Boolean values.

Remarks

The following table contains the properties that do not exist in the Properties collection for TableDef or QueryDef objects until you add them using the CreateProperty method or set them using the Formatting (Datasheet) toolbar.

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds all the properties listed with an asterisk to the Properties collection.

See Also

Setting Description

True (–1) The text is italic.

False (0) (Default) The text isn't italic.

Setting Description

True The text is underlined.

False (Default) The text isn't underlined.

l DatasheetBackColor l DatasheetCellsEffect

l DatasheetFontHeight* DatasheetFontItalic*

l DatasheetFontName* l DatasheetFontUnderline*

l DatasheetFontWeight* l DatasheetForeColor*

l DatasheetGridlinesBehavior l DatasheetGridlinesColor

Page 175: Microsoft Access Language

Microsoft Access Language Reference Página 175 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

BackColor property, DatasheetBackColor, DatasheetForeColor properties, DatasheetCellsEffect property, DatasheetFontName, DatasheetFontHeight properties, DatasheetFontWeight property, DatasheetGridlinesBehavior property, DatasheetGridlinesColor property, ForeColor property.

Example

The following example displays the data and field names in Datasheet view of the Products form as italic and underlined.

Forms![Products].DatasheetFontItalic = TrueForms![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 dbs As Database, tdfProducts As TableDefSet dbs = CurrentDbSet tdfProducts = dbs![Products]SetTableProperty tdfProducts, "DatasheetFontItalic", dbBoolean, TrueSetTableProperty tdfProducts, "DatasheetFontUnderline", dbBoolean, True

Sub SetTableProperty(tdfTableObj 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 prpProperty As Property On Error Resume Next ' Don't trap errors. tdfTableObj.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 '" & tdfTableObj.Name & "'", 48, _ "SetTableProperty" Else On Error GoTo 0 Set prpProperty = tdfTableObj.CreateProperty(strPropertyName, _ intPropertyType, varPropertyValue) tdfTableObj.Properties.Append prpProperty End If End If tdfTableObj.Properties.RefreshEnd Sub

DatasheetFontName, DatasheetFontHeight Properties

Applies To

Form object, QueryDef object, TableDef object.

Description

Page 176: Microsoft Access Language

Microsoft Access Language Reference Página 176 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the DatasheetFontName and DatasheetFontHeight properties to specify the font and the font point size used to display and print field names and data in Datasheet view.

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

l The DatasheetFontName property. In Visual Basic, a string expression equal to the name of the font.

l The DatasheetFontHeight property. In Visual Basic, an Integer value between 1 and 127 representing the font size in points.

You can set these properties by selecting the font name from the Font box or font size from the Font Size box on the Formatting (Datasheet) toolbar.

You can also set these properties with the Font and Size boxes in the Font dialog box, available 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 font size you specify must be valid for the font specified by the DatasheetFontName property. For example, MS Sans Serif is available only in sizes 8, 10, 12, 14, 18, and 24 points.

You can set the default DatasheetFontName and DatasheetFontHeight properties by using the settings under Default Font on the Datasheet tab of the Options dialog box, available by clicking Options on the Tools menu.

The following table contains the properties that do not exist in the Properties collection for TableDef or QueryDef objects until you add them using the CreateProperty method or set them using the Formatting (Datasheet) toolbar.

l DatasheetBackColor l DatasheetCellsEffect

l DatasheetFontHeight* DatasheetFontItalic*

l DatasheetFontName* l DatasheetFontUnderline*

l DatasheetFontWeight* l DatasheetForeColor*

Page 177: Microsoft Access Language

Microsoft Access Language Reference Página 177 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds all the properties listed with an asterisk to the Properties collection.

See Also

BackColor property, DatasheetBackColor, DatasheetForeColor properties, DatasheetCellsEffect property, DatasheetFontItalic, DatasheetFontUnderline properties, DatasheetFontWeight property, DatasheetGridlinesBehavior property, DatasheetGridlinesColor property, FillColor property.

Example

The following example sets the font to MS Serif, the font size to 10 points, 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 dbs As Database, tdfProducts As TableDefSet dbs = CurrentDbSet tdfProducts = dbs!ProductsSetTableProperty tdfProducts, "DatasheetFontName", dbText, "MS Serif"SetTableProperty tdfProducts, "DatasheetFontHeight", dbInteger, 10SetTableProperty tdfProducts, "DatasheetFontWeight", dbInteger, 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 = 10Forms!Products.DatasheetFontWeight = 500

DatasheetFontUnderline Property

See DatasheetFontItalic, DatasheetFontUnderline Properties.

DatasheetFontWeight Property

Applies To

Form object, QueryDef object, TableDef object.

Description

You can use the DatasheetFontWeight property to specify the line width of the font used to

l DatasheetGridlinesBehavior l DatasheetGridlinesColor

Page 178: Microsoft Access Language

Microsoft Access Language Reference Página 178 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

You can also set Normal and Bold for this property in the Font dialog box, available by clicking Font on the Format menu in Datasheet view. In the Font dialog box's Font Style box, the only available font weight settings are Regular (identical to Normal) and Bold.

Another method of setting only the Regular and Bold settings is to click the Bold button on the Formatting (Datasheet) toolbar.

You can set the default DatasheetFontWeight property by using the settings under Default Font on the Datasheet tab of the Options dialog box, available by clicking Options on the Tools menu.

The following table contains the properties that do not exist in the Properties collection for TableDef or QueryDef objects until you add them using the CreateProperty method or set them using the Formatting (Datasheet) toolbar.

Setting Description

100 Thin

200 Extra Light

300 Light

400 (Default) Normal

500 Medium

600 Semi-bold

700 Bold

800 Extra Bold

900 Heavy

Page 179: Microsoft Access Language

Microsoft Access Language Reference Página 179 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds all the properties listed with an asterisk to the Properties collection.

See Also

BackColor property, DatasheetBackColor, DatasheetForeColor properties, DatasheetCellsEffect property, DatasheetFontItalic, DatasheetFontUnderline properties, DatasheetFontName, DatasheetFontHeight properties, DatasheetGridlinesBehavior property, DatasheetGridlinesColor property, FillColor property.

Example

See the DatasheetFontName, DatasheetFontHeight properties example.

DatasheetForeColor Property

See DatasheetBackColor, DatasheetForeColor Properties.

DatasheetGridlinesBehavior Property

Applies To

Form object, QueryDef object, TableDef object.

Description

You can use the DatasheetGridlinesBehavior property to specify which gridlines will appear in Datasheet view.

l DatasheetBackColor l DatasheetCellsEffect

l DatasheetFontHeight* DatasheetFontItalic*

l DatasheetFontName* l DatasheetFontUnderline*

l DatasheetFontWeight* l DatasheetForeColor*

l DatasheetGridlinesBehavior l DatasheetGridlinesColor

Page 180: Microsoft Access Language

Microsoft Access Language Reference Página 180 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note This DatasheetGridlinesBehavior property applies only to objects in Datasheet view.

Setting

The DatasheetGridlinesBehavior property uses the following settings.

You can set this property by using the Gridlines button on the Formatting (Datasheet) toolbar, by using a macro, or by using Visual Basic.

You can also set this property by selecting the settings displayed under Gridlines Shown in the Cells Effects dialog box, available by clicking Cells on the Format menu.

You can set the default DatasheetGridlinesBehavior property by using the settings under Default Gridlines Showing on the Datasheet tab of the Options dialog box, available by clicking Options on the Tools menu.

Remarks

Changes to this property will be visible only if the DatasheetCellsEffect property is set to Flat.

The following table contains the properties that do not exist in the Properties collection for TableDef or QueryDef objects until you add them using the CreateProperty method or set them using the Formatting (Datasheet) toolbar.

Setting Description Visual Basic Value

None No gridlines are displayed.

acGridlinesNone 0

Horizontal Only horizontal gridlines are displayed.

acGridlinesHoriz 1

Vertical Only vertical gridlines are displayed.

acGridlinesVert 2

Both (Default) Horizontal and vertical gridlines are displayed.

acGridlinesBoth 3

Page 181: Microsoft Access Language

Microsoft Access Language Reference Página 181 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds all the properties listed with an asterisk to the Properties collection.

See Also

BackColor property, DatasheetBackColor, DatasheetForeColor properties, DatasheetCellsEffect property, DatasheetFontItalic, DatasheetFontUnderline properties, DatasheetFontName, DatasheetFontHeight properties, DatasheetFontWeight property, DatasheetGridlinesColor property, FillColor property.

DatasheetGridlinesColor Property

Applies To

Form object, QueryDef object, TableDef object.

Description

You can use the DatasheetGridlinesColor property to specify the color of gridlines in a datasheet.

Note The DatasheetGridlinesColor property applies only to objects in Datasheet view.

Setting

The DatasheetGridlinesColor property setting is a Long Integer value. In Visual Basic, you can also use the RGB or QBColor functions to set this property.

You can set this property by using the Line Color button on the Formatting (Datasheet) toolbar, by using a macro, or by using Visual Basic.

You can also set this property by clicking Cells on the Format menu and displaying the Cells Effects dialog box. You can then select an available color from the drop-down list under Gridline

l DatasheetBackColor l DatasheetCellsEffect

l DatasheetFontHeight* DatasheetFontItalic*

l DatasheetFontName* l DatasheetFontUnderline*

l DatasheetFontWeight* l DatasheetForeColor*

l DatasheetGridlinesBehavior l DatasheetGridlinesColor

Page 182: Microsoft Access Language

Microsoft Access Language Reference Página 182 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Color.

You can set the default DatasheetGridlinesColor property by using the settings under Default Colors on the Datasheet tab of the Options dialog box, available by clicking Options on the Tools menu.

Remarks

This property setting affects the gridline color for the entire datasheet. It's not possible to set the gridline color of individual cells in Datasheet view.

The following table contains the properties that do not exist in the Properties collection for TableDef or QueryDef objects until you add them using the CreateProperty method or set them using the Formatting (Datasheet) toolbar.

Note When you add or set any property listed with an asterisk, Microsoft Access automatically adds all the properties listed with an asterisk to the Properties collection.

See Also

BackColor property, DatasheetBackColor, DatasheetForeColor properties, DatasheetCellsEffect property, DatasheetFontItalic, DatasheetFontUnderline properties, DatasheetFontName, DatasheetFontHeight properties, DatasheetFontWeight property, DatasheetGridlinesBehavior property, FillColor property.

DataType Property

Applies To

Table field.

Description

l DatasheetBackColor l DatasheetCellsEffect

l DatasheetFontHeight* DatasheetFontItalic*

l DatasheetFontName* l DatasheetFontUnderline*

l DatasheetFontWeight* l DatasheetForeColor*

l DatasheetGridlinesBehavior l DatasheetGridlinesColor

Page 183: Microsoft Access Language

Microsoft Access Language Reference Página 183 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the DataType property to specify the type of data stored in a table field. Each field can store data consisting of only a single data type.

Setting

The DataType property uses the following settings.

(continued)

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 65,535 characters. (If the Memo field is manipulated through DAO and only text and numbers [not binary data] will be stored in it, then the size of the Memo field is limited by the size of the database.)

Number Numeric data used in mathematical calculations. For more information on how to set the specific Number type, see the FieldSize property.

1, 2, 4, or 8 bytes (16 bytes if the FieldSize property is set to Replication ID).

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 and to 4 digits on the right side.

8 bytes.

Page 184: Microsoft Access Language

Microsoft Access Language Reference Página 184 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

4 bytes (16 bytes if the FieldSize property is set to Replication ID).

Yes/No Yes and No values and fields that contain only one of two values (Yes/No, True/False, or 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)

Hyperlink Text or combinations of text and numbers stored as text and used as a hyperlink address. A hyperlink address can have up to three parts:

displaytext — the text that appears in a field or control.

address — the path to a file (UNC path) or page (URL).

subaddress — a location within the file or page.

Each part of the three parts of a Hyperlink data type can contain up to 2048 characters.

Page 185: Microsoft Access Language

Microsoft Access Language Reference Página 185 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property only in the upper portion of table Design view.

In Visual Basic, you can use the DAO Type property to set a field's data type before appending it to the Fields collection.

Remarks

Memo, Hyperlink, 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 predefined display format for Number, Date/Time, Currency, and Yes/No data types.

For more information about choosing a field data type, see Chapter 4, "Working with Variables, Data Types, and Constants," in Building Applications with Microsoft Access 97.

See Also

The easiest way to insert a hyperlink address in a field or control is to click Hyperlink on the Insert menu.

Lookup Wizard

Creates a field that allows you to choose a value from another table or from a list of values by using a list box or combo box. Clicking this option starts the Lookup Wizard, which creates a Lookup field. After you complete the wizard, Microsoft Access sets the data type based on the values selected in the wizard.

The same size as the primary key field used to perform the lookup, typically 4 bytes.

Page 186: Microsoft Access Language

Microsoft Access Language Reference Página 186 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

CreateField method ("DAO Language Reference"), FieldSize property, Format property, HyperlinkPart function, InputMask property, NewValues property, Size property ("DAO Language Reference"), Type property ("DAO Language Reference").

DateGrouping Property

Applies To

Report.

Description

You can use the DateGrouping property to specify how you want to group dates in a report. For example, using the US Defaults setting will cause the week to begin on Sunday. If you set a Date/Time field's GroupOn property to Week, the report will group dates from Sunday to Saturday.

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.

You can set this property by using 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.

Setting Description Visual Basic

US Defaults Microsoft Access uses the U.S. settings for the first day of the week (Sunday) and the first week of the year (starts on January 1).

0

Use System Settings

(Default) Microsoft Access uses settings based on the locale selected in the Regional Settings Properties dialog box in Windows Control Panel.

1

Page 187: Microsoft Access Language

Microsoft Access Language Reference Página 187 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

Date function, GroupOn property.

DAvg Function

Description

You can use the DAvg function to calculate the average of a set of values in a specified set of records (a domain). Use the DAvg function in Visual Basic code or in a macro, in a query expression, or in a calculated control.

For example, you could use the DAvg function in the criteria row of a select query on freight cost to restrict the results to those records where the freight cost exceeds the average. Or you could use an expression including the DAvg function 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 has the following arguments.

Argument Description

expr An 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. In expr, you can include the name of a field in a table, 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 A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

Page 188: Microsoft Access Language

Microsoft Access Language Reference Página 188 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

Records containing Null values aren't included in the calculation of the average.

Whether you use the DAvg function 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 the DAvg function 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, Order Details, 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 the DAvg function within a calculated field expression in a query, or in the Update To row of an update query.

Note You can use either the DAvg or Avg function in a calculated field expression in a totals query. If you use the DAvg function, values are averaged before the data is grouped. If you use the Avg function, the data is grouped before values in the field expression are averaged.

Use the DAvg function in a calculated control when you need to specify criteria to restrict the range of data on which the DAvg function 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 the DAvg function in a module or macro or in a calculated control on a form if a field that you need to display isn't 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 the DAvg function to perform this calculation and display the data on your form.

Tips

criteria An optional string expression used to restrict the range of data on which the DAvg function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DAvg function evaluates expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise the DAvg function returns a Null.

Page 189: Microsoft Access Language

Microsoft Access Language Reference Página 189 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l If you use the DAvg function 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.

l If the data type of the field from which expr is derived is a number, the DAvg function returns a Double data type. If you use the DAvg function in a calculated control, include a data type conversion function in the expression to improve performance.

l Although you can use the DAvg function 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 aren't 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 clicking Save Record on the File menu, moving the focus to another record, or by using the Update method.

See Also

Avg function ("SQL Language Reference"), DCount function, DSum function.

Example

The following example returns the average freight cost for orders shipped to the United Kingdom on or after January 1, 1996. 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 or equal to 1-1-96. 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 function calculation will have both of these criteria.

Dim dblX As DoubledblX = DAvg("[Freight]", "Orders", _ "[ShipCountry] = 'UK' AND [ShippedDate] >= #1-1-96#")

The next example calculates an average by 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 StringstrCountry = "UK"dblX = DAvg("[Freight]", "Orders", _ "[ShipCountry] = '" & strCountry & "'OR [ShippedDate] >= #1-1-96#")

DBEngine Property

Applies To

Application object.

Description

Page 190: Microsoft Access Language

Microsoft Access Language Reference Página 190 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 in all views.

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 Objects model and it contains and controls all other objects in the hierarchy of Data Access Objects.

See Also

Application property, DBEngine object ("DAO Language Reference").

Example

See the Application property example.

DblClick Event

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Form section, Image control, Label control, List Box control, Option Button control, Option Group control, Page, Rectangle control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

The DblClick event occurs when the user presses and releases the left mouse button twice over an object within the double-click time limit of the system.

On a form, the DblClick event occurs when the user double-clicks a blank area or record selector on 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

l The DblClick event applies only to forms, form sections, and controls on a form, not controls on a report.

l 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.

l 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

Page 191: Microsoft Access Language

Microsoft Access Language Reference Página 191 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

effect as double-clicking the associated control. The normal events for the control occur, not any events for the attached label.

Remarks

To run a macro or event procedure when this event occurs, set the OnDblClick property to the name of the macro or to [Event Procedure].

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 setting under Double-Click Speed on the Buttons tab of the Mouse option of 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 or event procedure 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. Note that, generally speaking, double-clicking a command button should be discouraged.

If you double-click any other control besides a command button, the second Click event doesn't occur.

See Also

Click event, Event properties, MouseDown, MouseUp events.

DblClick Event — Event Procedures

Description

Page 192: Microsoft Access Language

Microsoft Access Language Reference Página 192 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To create an event procedure that runs 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 has the following arguments.

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 run in response to double-clicking an embedded object before an OLE server 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 the OLE server.

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:

MouseDown MouseUp Click DblClick MouseUp 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 runs again. The following example cancels the second Click event:

Private Sub CmdButton_DblClick(Cancel As Integer) Cancel = True ' Cancel the second Click event.End Sub

See Also

Argument Description

controlname The name of the control whose DblClick event procedure you want to run.

Cancel The setting determines if the DblClick event occurs. Setting the Cancel argument to True (–1) cancels the DblClick event.

Page 193: Microsoft Access Language

Microsoft Access Language Reference Página 193 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DblClick event — macros.

Example

The following example shows how you can use a DblClick event procedure to open a form that displays records from the table that is the row source of a combo box. When the user double-clicks the Salesperson combo box in an Orders form, the Employees form is displayed, showing the record for the employee selected in the combo box.

To try the example, add the following event procedure to a form named Orders that contains a combo box named EmployeeID. The combo box should have as its row source the same table that is the source for the Employees form (or a query based on that table).

Private Sub EmployeeID_DblClick(Cancel As Integer) DoCmd.OpenForm "Employees", , , _ "EmployeeID = Forms!Orders!EmployeeID"End Sub

DblClick Event — Macros

Description

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 server 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 would run 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 OLE 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.

See Also

DblClick event — event procedures.

DCount Function

Page 194: Microsoft Access Language

Microsoft Access Language Reference Página 194 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the DCount function to determine the number of records that are in a specified set of records (a domain). Use the DCount function in Visual Basic, a macro, a query expression, or a calculated control.

For example, you could use the DCount function 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 has the following arguments.

Remarks

Argument Description

expr An 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. In expr, you can include the name of a field in a table, 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 A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria An optional string expression used to restrict the range of data on which the DCount function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DCount function evaluates expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise the DCount function returns a Null.

Page 195: Microsoft Access Language

Microsoft Access Language Reference Página 195 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Use the DCount function 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, the DCount function simply tallies the number of records. The value of any calculation performed by expr is unavailable.

Whether you use the DCount function 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 the DCount function 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 the Count function in a query expression instead of the DCount function, and set optional criteria to enforce any restrictions on the results. Use the DCount function when you must count records in a domain from within a code module or macro, or in a calculated control.

You can use the DCount function to count the number of records containing a particular field that isn't 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, the DCount function 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, the DCount function returns the number of records containing data in any of the listed fields. If you use the addition operator, the DCount function returns only the number of records containing data in all of the listed fields. The following example demonstrates the effects of each operator when used with a field that contains data in all records (ShipName) and a field that contains no data (ShipRegion).

intW = DCount("[ShipName]", "Orders") ' Returns 831.intX = DCount("[ShipRegion]", "Orders") ' Returns 323.intY = DCount("[ShipName] + [ShipRegion]", "Orders") ' Returns 323.intZ = DCount("[ShipName] & [ShipRegion]", "Orders") ' Returns 831.

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.

Page 196: Microsoft Access Language

Microsoft Access Language Reference Página 196 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Unsaved changes to records in domain aren't 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 by using the Update method.

See Also

Count function ("SQL Language Reference"), DAvg function, DSum function.

Example

The following 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 isn't 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#")

DDE Function

Description

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.

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 has the following arguments.

Page 197: Microsoft Access Language

Microsoft Access Language Reference Página 197 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 can't 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 can't 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

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, such as Microsoft Excel. 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. The topic argument 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.

Page 198: Microsoft Access Language

Microsoft Access Language Reference Página 198 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

conversations has already been reached, the DDE function returns a Null.

Note The other application may be configured to ignore your request for a DDE conversation. If so, the DDE function 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 Automation.

The following table illustrates how the DDE function behaves when you use it with each of the controls.

(continued)

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, the DDE function returns the first entry. You could use this 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 regions or countries that you maintain in a Microsoft Excel worksheet.

Control Remarks

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 the DDE function returns 2, the second button will be selected. If this function returns a value that doesn't match any of the OptionValue property settings, none of the buttons will be

Page 199: Microsoft Access Language

Microsoft Access Language Reference Página 199 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

DDEExecute statement, DDEInitiate function, DDEPoke statement, DDERequest function, DDESend function, DDETerminate statement, DDETerminateAll statement, Enabled, Locked properties.

Example

The following 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.

Sub ExcelDDE() Dim intI As Integer, intChan1 As Integer Dim strTopics As String, strResp As String, strSheetName As String

On Error Resume Next ' Set up error handling.

intChan1 = DDEInitiate("Excel", "System") ' Establish link. If Err Then ' If error occurs, Excel may Err = 0 ' not be running. Reset error Shell "C:\Excel\Excel.exe", 1 ' and start spreadsheet. If Err Then Exit Sub ' If another error, exit. ' Establish Spreadsheet link. intChan1 = DDEInitiate("Excel", "System") End If

' Create new worksheet. DDEExecute intChan1, "[New(1)]" ' Get topic list, worksheet name. strTopics = DDERequest(intChan1, "Selection") strSheetName = Left(strTopics, InStr(1, strTopics, "!") - 1) ' Terminate DDE link. DDETerminate intChan1 ' Establish link with new worksheet. intChan1 = DDEInitiate("Excel", strSheetName) For intI = 1 To 10 ' Put some values into DDEPoke intChan1, "R1C" & intI, intI ' first row. Next intI ' Make chart. DDEExecute intChan1, "[Select(""R1C1:R1C10"")][New(2,2)]"

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, the DDE function returns the first entry.

Check box If the DDE function returns 0, the check box will be cleared. If this function 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.

Page 200: Microsoft Access Language

Microsoft Access Language Reference Página 200 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' Terminate all links. DDETerminateAllEnd Sub

DDEExecute Statement

Description

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've 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 has the following arguments.

Remarks

The value of the command argument depends on the application and topic specified when the channel indicated by the channum argument is opened. An error occurs if the channum argument 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.

Tip If you need to manipulate another application's objects from Microsoft Access, you may want to consider using Automation.

Argument Description

channum A channel number, the long integer 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.

Page 201: Microsoft Access Language

Microsoft Access Language Reference Página 201 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

DDE function, DDEInitiate function, DDEPoke statement, DDERequest function, DDESend function, DDETerminate statement, DDETerminateAll statement.

Example

See the DDE function example.

DDEInitiate Function

Description

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 the following arguments.

Remarks

Argument Description

application A string expression identifying an application that can participate in a DDE conversation. Usually, the application argument 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 the application argument. Check the application's documentation for a list of topics.

Page 202: Microsoft Access Language

Microsoft Access Language Reference Página 202 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

If successful, the DDEInitiate function begins a DDE conversation with the application and topic specified by the application and topic arguments, and then returns a Long integer value. This return value 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 isn't already running or if it's running but doesn't recognize the topic argument or doesn't support DDE, the DDEInitiate function returns a run-time error.

The value of the topic argument depends on the application specified by the application argument. 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 Microsoft Windows and your computer's memory and resources. If you aren't using a channel, you should conserve resources by terminating it with a DDETerminate or DDETerminateAll statement.

Tip If you need to manipulate another application's objects from Microsoft Access, you may want to consider using Automation.

See Also

DDE function, DDEExecute statement, DDEPoke statement, DDERequest function, DDESend function, DDETerminate statement, DDETerminateAll statement.

Example

See the DDE function example.

DDEPoke Statement

Description

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 has the following arguments.

Page 203: Microsoft Access Language

Microsoft Access Language Reference Página 203 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The value of the item argument depends on the application and topic specified when the channel indicated by the channum argument is opened. For example, the item argument may be a range of cells in a Microsoft Excel spreadsheet.

The string contained in the data argument must be an alphanumeric text string. No other formats are supported. For example, the data argument could be a number to fill a cell in a specified range in an Excel worksheet.

If the channum argument isn't an integer corresponding to an open channel or if the other application doesn't recognize or accept the specified data, a run-time error occurs.

Tip If you need to manipulate another application's objects from Microsoft Access, you may want to consider using Automation.

See Also

DDE function, DDEExecute statement, DDEInitiate function, DDERequest function, DDESend function, DDETerminate statement, DDETerminateAll statement.

Example

See the DDE function example.

DDERequest Function

Description

Argument Description

channum A channel number, an integer returned by the DDEInitiate function.

item A string expression that's the name of a data item recognized by the application specified by the DDEInitiate function. Check the application's documentation for a list of possible items.

data A string containing the data to be supplied to the other application.

Page 204: Microsoft Access Language

Microsoft Access Language Reference Página 204 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 has the following arguments.

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 the item argument depends on the application and topic specified when the channel indicated by the channum argument is opened. For example, the item argument may be a range of cells in a Microsoft Excel spreadsheet.

The DDERequest function returns a Variant as a string containing the requested information if the request was successful.

The data is requested in alphanumeric text format. Graphics or text in any other format can't be transferred.

If the channum argument isn't an integer corresponding to an open channel, or if the data requested can't be transferred, a run-time error occurs.

Tip If you need to manipulate another application's objects from Microsoft Access, you may want to consider using Automation.

See Also

Argument Description

channum A channel number, an integer returned by the DDEInitiate function.

item A string expression that's the name of a data item recognized by the application specified by the DDEInitiate function. Check the application's documentation for a list of possible items.

Page 205: Microsoft Access Language

Microsoft Access Language Reference Página 205 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DDE function, DDEExecute statement, DDEInitiate function, DDEPoke statement, DDESend function, DDETerminate statement, DDETerminateAll statement.

Example

See the DDE function example.

DDESend Function

Description

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.

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.

(continued)

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, such as Microsoft Excel. 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. The topic argument is often a document or data file. Check the other application's documentation for a list of possible topics.

Page 206: Microsoft Access Language

Microsoft Access Language Reference Página 206 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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, the DDESend function 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 to an expression including the DDESend function, where data is the name of the bound control. For example, 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 the DDESend function, 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.

Argument Description

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.

data A string or expression containing the data to send to application.

Page 207: Microsoft Access Language

Microsoft Access Language Reference Página 207 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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, the DDESend function returns a Null.

Note The other application may be configured to ignore your request for a DDE conversation. If so, the DDESend function 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 Automation.

The following table illustrates how the DDESend function behaves when you use it with each of the controls.

Control Remarks

Text box or Combo box

Because the text box or 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, the DDESend function doesn't send the information and item isn't changed.

Page 208: Microsoft Access Language

Microsoft Access Language Reference Página 208 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

DDE function, DDEExecute statement, DDEInitiate function, DDEPoke statement, DDERequest function, DDETerminate statement, DDETerminateAll statement, Enabled, Locked properties.

DDETerminate Statement

Description

You can use the DDETerminate statement to close a specified dynamic data exchange (DDE) channel.

For example, if you've 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 channum argument specifies the channel number to close. It refers to a channel opened by the DDEInitiate function. If the channum argument isn't an integer corresponding to an open channel, a run-time error occurs.

Once a channel is closed, any subsequent DDE functions or statements performed on that channel cause a run-time 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 Automation.

See Also

Check box The check box is shaded 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, the DDESend function doesn't send the information and item isn't changed.

Page 209: Microsoft Access Language

Microsoft Access Language Reference Página 209 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DDE function, DDEExecute statement, DDEInitiate function, DDEPoke statement, DDERequest function, DDESend function, DDETerminateAll statement.

Example

See the DDE function example.

DDETerminateAll Statement

Description

You can use the DDETerminateAll statement to close all open dynamic data exchange (DDE) channels.

For example, suppose you've 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 a run-time error.

Tips

l 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 (lower) pane of the Debug window while debugging code that performs DDE.

l If you need to manipulate another application's objects from Microsoft Access, you may want to consider using Automation.

See Also

DDE function, DDEExecute statement, DDEInitiate function, DDEPoke statement, DDERequest function, DDESend function, DDETerminate statement.

Example

See the DDE function example.

Page 210: Microsoft Access Language

Microsoft Access Language Reference Página 210 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Deactivate Event

See Activate, Deactivate Events.

DecimalPlaces Property

Applies To

Combo Box control, Field object, Query field, Table field, Text Box control.

Description

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.

You can set this property for text boxes and combo boxes by using the control's property sheet and for table fields by using the table's property sheet. You can also set this property in the Field Properties property sheet in query Design view.

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.

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

Page 211: Microsoft Access Language

Microsoft Access Language Reference Página 211 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

For controls, you can also set this property by 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 in table Design view.

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.

See Also

FieldSize property, Format property.

Default Property

Applies To

ActiveX control, Command Button control.

Description

You can use the Default property to specify whether a command button is the default button on a form.

Setting

The Default property uses the following settings.

You can set this property by using the command button's property sheet, a macro, or Visual Basic.

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)

Page 212: Microsoft Access Language

Microsoft Access Language Reference Página 212 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

When the command button's Default property setting is Yes and the Form window is active, the user can choose the command button by pressing ENTER (if no other command button has the focus) as well as by clicking the command button.

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.

See Also

Cancel property, Click event.

DefaultControl Method

Applies To

Form object, Report object.

Description

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 has the following arguments.

Argument Description

control A Control object for which the default properties are to be set.

Page 213: Microsoft Access Language

Microsoft Access Language Reference Página 213 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 can be used only in 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, list the Properties collection of the Control object returned by the DefaultControl method.

See Also

Control object, ControlType property, CreateControl, CreateReportControl functions.

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()

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.

Page 214: Microsoft Access Language

Microsoft Access Language Reference Página 214 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.RestoreEnd Sub

DefaultValue Property

Applies To

Check Box control, Combo Box control, List Box control, Option Button control, Option Group control, Table field, Text Box control, Toggle Button control.

Description

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

l The DefaultValue property doesn't apply to check box, option button, or toggle button controls when they are in an option group. It does apply to the option group itself.

l 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's automatically entered in a control or 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 date and time. The maximum length for a DefaultValue property setting is 255 characters.

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 (in the Field Properties section), in a macro, or by using 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":

Page 215: Microsoft Access Language

Microsoft Access Language Reference Página 215 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Forms!frmInvoice!PaymentMethod.DefaultValue = """Cash"""

Note To set this property for a field by using Visual Basic, use the DAO DefaultValue property.

Remarks

The DefaultValue property is applied only when you add a new record. If you change the DefaultValue property, the change isn't automatically applied to existing records.

If you set the DefaultValue property for a form control that's bound to a field that also has a DefaultValue property setting defined in the table, the control setting overrides the table setting.

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 although the control's DefaultValue property setting will remain blank.

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 control'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's the source of the default value must appear earlier in the tab order than the control containing the expression.

See Also

AllowZeroLength property, DefaultValue property ("DAO Language Reference"), Required property, Value property.

DefaultView, ViewsAllowed Properties

Applies To

Form.

Description

l You can use the DefaultView property to specify the opening view of a form.l You can use the ViewsAllowed property to specify whether users can switch between

Datasheet view and Form view by clicking the Form View or Datasheet View command on the View menu or by clicking the arrow next to the View button and clicking Form View or Datasheet View.

Setting

The DefaultView property uses the following settings.

Page 216: Microsoft Access Language

Microsoft Access Language Reference Página 216 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The ViewsAllowed property uses the following settings.

Design view is always available (unless permissions are set otherwise).

You can set these properties by using the form's property sheet, a macro, or Visual Basic.

Remarks

The views displayed in the View button list and on the View menu depend on the setting of the ViewsAllowed property. For example, if the ViewsAllowed property is set to Datasheet, Form View is disabled in the View button list and on the View menu.

The combination of these properties creates the following conditions.

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 form's detail section.

1

Datasheet Displays the form fields arranged in rows and columns like a spreadsheet.

2

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

Page 217: Microsoft Access Language

Microsoft Access Language Reference Página 217 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

See Also

AllowAdditions property, AllowDeletions property, AllowEdits property, AutoResize property, DataEntry property, OpenForm action.

DefaultWorkspaceClone Method

Applies To

Application object.

Description

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.

DefaultView ViewsAllowed Description

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.

Page 218: Microsoft Access Language

Microsoft Access Language Reference Página 218 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the DefaultWorkspaceClone method to create a new Workspace object without requiring the user to log on 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 has the following argument.

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 on. The Workspace object clone is equivalent to the Workspace object that would be created if the same user logged on again with the same password.

See Also

BeginTrans, CommitTrans, Rollback methods ("DAO Language Reference"), Name property ("DAO Language Reference"), Password property ("DAO Language Reference"), User object, Users collection.

Example

The following example clones the default Workspace object, then lists the properties of each Workspace object.

Sub CloneWorkspace() Dim wrkDefault As Workspace, wrkClone As Workspace Dim prp As Property On Error Resume Next ' 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

Argument Description

application The Application object.

Page 219: Microsoft Access Language

Microsoft Access Language Reference Página 219 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Debug.Print ">>>"; prp.Name; " "; prp.Value Next prpEnd Sub

Delete, BeforeDelConfirm, AfterDelConfirm Events

Applies To

Form.

Description

l The Delete event occurs when the user performs some action, such as pressing the DEL key, to delete a record, but before the record is actually deleted.

l The BeforeDelConfirm event occurs after the user deletes to the buffer one or more records, but before Microsoft Access displays a dialog box asking the user to confirm the deletions.

l The AfterDelConfirm event occurs after the user confirms the deletions and the records are actually deleted or when the deletions are canceled.

Remarks

To run a macro or event procedure when these events occur, set the OnDelete, BeforeDelConfirm, or AfterDelConfirm property to the name of the macro or to [Event Procedure].

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, with a Delete event occurring for each record), but before the Delete Confirm dialog box is displayed. Canceling the BeforeDelConfirm event restores the record or records from the buffer and prevents the Delete Confirm dialog box from being displayed.

The AfterDelConfirm event occurs after a record or records are actually deleted or after a deletion or deletions are 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. For example, 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.

Note The BeforeDelConfirm and AfterDelConfirm events don't occur and the Delete Confirm dialog box isn't displayed if you clear the Record Changes check box under Confirm on the Edit/Find tab of the Options dialog box, available by clicking Options on the Tools menu.

By running a macro or 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.

Page 220: Microsoft Access Language

Microsoft Access Language Reference Página 220 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To delete a record, you can click Delete Record on the Edit menu. This deletes the current record (the record indicated by the record selector). You can also click the record selector or click Select Record on the Edit menu to select the record, and then press the DEL key to delete it. If you click Delete Record, the record selector of the current record, or 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 the Delete Confirm dialog box asking you to confirm the deletion. After you respond to the dialog box by confirming or canceling the deletion, the AfterDelConfirm event occurs.

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.

See Also

BeforeUpdate, AfterUpdate events, Current event, Event properties.

Delete, BeforeDelConfirm, AfterDelConfirm Events — Event Procedures

Description

To create an event procedure that runs 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 has the following argument.

Page 221: Microsoft Access Language

Microsoft Access Language Reference Página 221 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The BeforeDelConfirm event procedure has the following arguments.

(continued)

Argument Description

Cancel The setting determines if the Delete event occurs. Setting the Cancel argument to True (–1) cancels the Delete event.

Argument Description

Cancel The setting determines if the BeforeDelConfirm event occurs. Setting the Cancel argument to True 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, the Response argument is ignored.

If Cancel is set to False (0), which it is by default, the value in the Response argument is used by Microsoft Access to determine the type of response to the delete event.

Response The setting determines whether Microsoft Access displays the Delete Confirm dialog box asking if the record should be deleted. The Response argument can be set to one of the following intrinsic constants:

Constant Description

Page 222: Microsoft Access Language

Microsoft Access Language Reference Página 222 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The AfterDelConfirm event procedure has the following argument.

acDataErrContinue Continues without displaying the Delete Confirm dialog box. Setting the Cancel argument to False and the Response argument to acDataErrContinue enables Microsoft Access to delete records without prompting the user.

acDataErrDisplay (Default) Displays the Delete Confirm dialog box.

Argument Description

Status The setting indicates whether a record has been deleted. The Status argument can be any of the following intrinsic constants:

Constant Description

acDeleteOK Indicates the deletion was successful.

acDeleteCancel Indicates the deletion was canceled in Visual Basic.

Page 223: Microsoft Access Language

Microsoft Access Language Reference Página 223 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 set of temporary variables. 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 clear the temporary variables, or save the employee information in another table.

See Also

Delete, BeforeDelConfirm, AfterDelConfirm events — macros.

Example

The following example shows how you can prevent a user from deleting records from a table.

To try this example, add the following event procedure to a form that is based on a table. Switch to form 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 Delete Confirm 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 the example, add the following event procedure to 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 IfEnd Sub

acDeleteUserCancel Indicates the deletion was canceled by the user.

Page 224: Microsoft Access Language

Microsoft Access Language Reference Página 224 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 SelectEnd Sub

Delete, BeforeDelConfirm, AfterDelConfirm Events — Macros

Description

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 the Delete Confirm 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.

See Also

Delete, BeforeDelConfirm, AfterDelConfirm events — event procedures.

DeleteControl, DeleteReportControl Statements

Description

l The DeleteControl statement deletes a specified control from a form.l The DeleteReportControl statement deletes a specified control from a report.

For example, suppose you have a procedure that must be run the first time each user logs onto

Page 225: Microsoft Access Language

Microsoft Access Language Reference Página 225 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Remarks

The DeleteControl and DeleteReportControl statements are available only in form Design view or report Design view, respectively.

Note 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.

See Also

CreateControl, CreateReportControl functions.

Example

The following example creates a form with a command button and displays a message that asks if the user wants to delete the command button. If the user clicks 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.

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.

Page 226: Microsoft Access Language

Microsoft Access Language Reference Página 226 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ctlNew.SizeToFit ' Prompt user to delete control. strMsg = "About to delete " & ctlNew.Name &". Continue?" ' Define buttons to be displayed in dialog box. intDialog = vbYesNo + vbCritical + vbDefaultButton2 intResponse = MsgBox(strMsg, intDialog) If intResponse = vbYes Then ' Delete control. DeleteControl frm.Name, ctlNew.Name End IfEnd Sub

DeleteLines Method

Applies To

Module object.

Description

The DeleteLines method deletes lines from a standard module or a class module.

Syntax

object.DeleteLines startline, count

The DeleteLines method has the following arguments.

Remarks

Lines in a module are numbered beginning with one. To determine the number of lines in a module, use the CountOfLines property.

To replace one line with another line, use the ReplaceLine method.

See Also

Argument Description

object A Module object.

startline A Long value that specifies the number of the line from which to begin deleting.

count A Long value that specifies the number of lines to delete.

Page 227: Microsoft Access Language

Microsoft Access Language Reference Página 227 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ReplaceLine method.

Example

The following example deletes a specified line from a module.

Function DeleteWholeLine(strModuleName, strText As String) As Boolean Dim mdl As Module, lngNumLines As Long Dim lngSLine As Long, lngSCol As Long Dim lngELine As Long, lngECol As Long Dim strTemp As String On Error GoTo Error_DeleteWholeLine DoCmd.OpenModule strModuleName Set mdl = Modules(strModuleName) If mdl.Find(strText, lngSLine, lngSCol, lngELine, lngECol) Then lngNumLines = Abs(lngELine - lngSLine) + 1 strTemp = LTrim$(mdl.Lines(lngSLine, lngNumLines)) strTemp = RTrim$(strTemp) If strTemp = strText Then mdl.DeleteLines lngSLine, lngNumLines Else MsgBox "Line contains text in addition to '" _ & strText & "'." End If Else MsgBox "Text '" & strText & "' not found." End If DeleteWholeLine = True Exit_DeleteWholeLine: Exit Function Error_DeleteWholeLine: MsgBox Err & " :" & Err.Description DeleteWholeLine = False Resume Exit_DeleteWholeLineEnd Function

You could call this function from a procedure such as the following, which searches the module Module1 for a constant declaration and deletes it.

Sub DeletePiConst() If DeleteWholeLine("Module1", "Const conPi = 3.14") Then Debug.Print "Constant declaration deleted successfully." Else Debug.Print "Constant declaration not deleted." End IfEnd Sub

DeleteObject Action

Description

You can use the DeleteObject action to delete a specified database object.

Setting

The DeleteObject action has the following arguments.

Page 228: Microsoft Access Language

Microsoft Access Language Reference Página 228 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Warning If you leave the Object Type and Object Name arguments blank, Microsoft Access deletes 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.

To run the DeleteObject action in Visual Basic, you can use the DeleteObject method of the DoCmd object.

See Also

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 argument 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 leave the Object Type argument blank, leave this argument blank also.

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

Page 229: Microsoft Access Language

Microsoft Access Language Reference Página 229 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DeleteObject method, SelectObject action.

DeleteObject Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Remarks

Argument Description

objecttype One of the following intrinsic constants:

acDefault (default)acFormacMacroacModuleacQueryacReportacTable

objectname A string expression that's the valid name of an object of the type selected by 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.

Page 230: Microsoft Access Language

Microsoft Access Language Reference Página 230 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

If you leave the objecttype and objectname arguments blank (the default constant, acDefault, is assumed for objecttype), 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).

See Also

DeleteObject action, SelectObject method.

Example

The following example deletes the specified table:

DoCmd.DeleteObject acTable, "Former Employees Table"

DeleteReportControl Statement

See DeleteControl, DeleteReportControl Statements.

Description Property

Applies To

Action query, Crosstab query, Field object, Parameter query, Query field, QueryDef object, Select query, SQL-Specific query, Table, Table field, TableDef object.

Description

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, click Properties on 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 when you click Details on the View menu.

For individual table or query fields, enter the field description in the upper portion of table Design view or in the Field Properties property sheet 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 by using the DAO CreateProperty method.

Remarks

Page 231: Microsoft Access Language

Microsoft Access Language Reference Página 231 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

An object's description is displayed in the Description column in the Details view of the Database window.

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.

See Also

Caption property, CreateProperty method ("DAO Language Reference"), Description property ("DAO Language Reference"), Object properties, StatusBarText property.

DestConnectStr, DestinationDB, DestinationTable Properties

Applies To

Action query.

Description

l The DestinationDB property specifies the type of application used to create an external database.

l The DestConnectStr property specifies 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).

l The DestinationTable property specifies the name of the table that will hold the results of the make-table or append 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 by 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's 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.

Page 232: Microsoft Access Language

Microsoft Access Language Reference Página 232 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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's property sheet or in SQL view of the Query window.

Remarks

When you click 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 query's property sheet to specify a table in a Microsoft Access database, enter the name of the table in the DestinationTable property box (for example, Clients). In the DestinationDB property box, enter the path and database name without the file name 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 DestinationTable property box. In the DestinationDB property box, enter the path (for example, C:\Pdoxdata). In the DestConnectStr property box, enter the specifier for the database type (for example, Paradox 3.x). For a list of specifiers, see the DAO Connect property.

To specify an Open Database Connectivity (ODBC) database, enter the name of the database in the DestConnectStr property 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 Help provided with the driver.

You don't need to set the DestinationDB property for ODBC databases.

For more information about accessing data in ODBC databases, see Chapter 18, "Accessing External Data," in Building Applications with Microsoft Access 97.

See Also

Connect property ("DAO Language Reference"), IN clause ("SQL Language Reference"), INSERT INTO statement ("SQL Language Reference")l, Source property, SourceConnectStr, SourceDatabase properties, TransferDatabase action.

Example

The following example appends the records in the Customer table to the Clients table in a Microsoft Access database named Clients in the C:\Data directory. You enter this SQL statement in SQL view of the Query window.

INSERT INTO Clients IN 'C:\Data\Clients.mdb'

Page 233: Microsoft Access Language

Microsoft Access Language Reference Página 233 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

SELECT Customer.[CompanyName], Customer.PhoneFROM Customer;

The next example creates a new table named Contacts in a Paradox version 3.x database in the C:\Pdoxdata directory.

SELECT Customer.CompanyName, Customer.PhoneINTO Contacts IN 'C:\Pdoxdata' [Paradox 3.x;] FROM Customer;

DFirst, DLast Functions

Description

You can use the DFirst and DLast functions to return a random record from a particular field in a table or query when you simply need any value from that field. Use the DFirst and DLast functions in a in a macro, module, query expression, or calculated control on a form or report.

Syntax

DFirst(expr, domain[, criteria])

DLast(expr, domain[, criteria])

The DFirst and DLast functions have the following arguments.

Argument Description

expr An expression that identifies the field from which you want to 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. In expr, you can include the name of a field in a table, 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 A string expression identifying the set of records that constitutes the domain.

Page 234: Microsoft Access Language

Microsoft Access Language Reference Página 234 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

Note If you want to return the first or last record in a set of records (a domain), 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. 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.

See Also

DLookup function, First, Last functions.

Dirty Property

Applies To

Form.

Description

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 uses the following settings.

criteria An optional string expression used to restrict the range of data on which the DFirst or DLast function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DFirst and DLast functions evaluate expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise, the DFirst and DLast functions return a Null.

Setting Description Visual Basic

True The current record has been changed.

True (–1)

Page 235: Microsoft Access Language

Microsoft Access Language Reference Página 235 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property is available in Form view and Datasheet view.

This property set or read using a macro or Visual Basic.

Remarks

When a record is saved, Microsoft Access sets the Dirty property to False. When a user makes changes to a record, the property is set to True.

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 by using the OldValue property.

Sub UndoEdits() If Me.Dirty Then Me!btnUndo.Enabled = True ' Enable button. Else Me!btnUndo.Enabled = False ' Disable button. End IfEnd Sub

Sub btnUndo_Click() Dim ctlC As Control ' For each control. For Each ctlC in Me.Controls If ctlC.ControlType = acTextBox Then ' Restore Old Value. ctlC.Value = ctlC.OldValue End If Next ctlCEnd Sub

DisplayControl Property

Applies To

Action query, Crosstab query, Parameter query, Query field, Select query, SQL-Specific query, Table field.

Description

You can use the DisplayControl property in table Design view to specify the default control you want to use for displaying a field.

Setting

You can set the DisplayControl property in the table's property sheet in table Design view by clicking the Lookup tab in the Field Properties section.

False The current record has not been changed.

False (0)

Page 236: Microsoft Access Language

Microsoft Access Language Reference Página 236 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property contains a drop-down list of the available controls for the selected field. For fields with a Text or Number data type, this property can be set to Text Box, List Box, or Combo Box. For fields with a Yes/No data type, this property can be set to Check Box, Text Box, or Combo Box.

Remarks

When you select a control for this property, any additional properties needed to configure the control are also displayed on the Lookup tab.

Tip You can let Microsoft Access set the DisplayControl property and any related properties for you when you select the Lookup Wizard as the data type for a field.

Setting this property and any related control type properties will affect the field display in both Datasheet view and Form view. The field is displayed by 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.

DisplayType Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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 Microsoft 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)

Page 237: Microsoft Access Language

Microsoft Access Language Reference Página 237 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the DisplayType property in a property sheet, in a macro, or by using Visual Basic. You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

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 (the default setting is Content or, if you select the Display As Icon check box, the setting is Icon).

Remarks

The DisplayType property determines the default setting of the Display As Icon check box in the Paste Special dialog box, available by clicking Paste Special on the Edit menu, and the Insert Object dialog box, displayed when inserting an unbound object frame. 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 by using the Object command on the Insert menu.

See Also

Action property.

DisplayWhen Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form section, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Rectangle control, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

You can use the DisplayWhen property to specify which of a form's sections or controls you want

Icon When the control contains an OLE object, the control displays the object's icon.

acOLEDisplayIcon (1)

Page 238: Microsoft Access Language

Microsoft Access Language Reference Página 238 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

displayed on screen and in print.

Note The DisplayWhen property applies only to the following form sections: detail, form header, and form footer. It also applies to all controls (except page breaks) on a form.

Setting

The DisplayWhen property uses the following settings.

You can set this property by using the object's property sheet, a macro, or Visual Basic.

For controls, you can set the default for this property by using the default control style or the DefaultControl method in Visual Basic.

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. You can also cancel the Format or Print event for a report section to prevent the section from being printed.

See Also

Enabled, Locked properties, Visible property.

DividingLines Property

Applies To

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

Page 239: Microsoft Access Language

Microsoft Access Language Reference Página 239 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Form.

Description

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.

You can set the DividingLines property by using the form's property sheet, a macro, or Visual Basic.

This property can be set in any view.

DLookup Function

Description

You can use the DLookup function to get the value of a particular field from a specified set of records (a domain). Use the DLookup function in Visual Basic, a macro, a query expression, or a calculated control on a form or report.

You can use the DLookup function to display the value of a field that isn't 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 the DLookup function in a calculated control to display the ProductName on the same form.

Syntax

DLookup(expr, domain[, criteria])

The DLookup function has the following arguments.

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)

Page 240: Microsoft Access Language

Microsoft Access Language Reference Página 240 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The DLookup function 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, the DLookup function returns a random value in the domain.

If no record satisfies criteria or if domain contains no records, the DLookup function returns a Null.

If more than one field meets criteria, the DLookup function returns the first occurrence. You should specify criteria that will ensure that the field value returned by the DLookup function is unique. You may want to use a primary key value for your criteria, such as [EmployeeID] in the following example, to ensure that the DLookup function returns a unique value:

Dim varX As VariantvarX = DLookup("[LastName]", "Employees", "[EmployeeID] = 1")

Argument Description

expr An 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. In expr, you can include the name of a field in a table, 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 A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria An optional string expression used to restrict the range of data on which the DLookup function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DLookup function evaluates expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise, the DLookup function returns a Null.

Page 241: Microsoft Access Language

Microsoft Access Language Reference Página 241 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Whether you use the DLookup function 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 the DLookup function 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 the DLookup function in an expression in a calculated control on a form or report if the field that you need to display isn't in the record source on which your form or report is based. For example, suppose you have an Order Details form based on an Order Details table with a text box called ProductID that displays the ProductID field. 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![Order Details]!ProductID)

Tips

l Although you can use the DLookup function 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 then to base your form or report on that query.

l You can also use the Lookup Wizard to find values in a foreign table.

Note Unsaved changes to records in domain aren't 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 clicking Save Record on the File menu, moving the focus to another record, or by using the Update method.

Example

The following 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 varX As VariantvarX = DLookup("[CompanyName]", "Shippers", "[ShipperID] = 1")

The next example from the Shippers table uses the form control ShipperID to provide criteria for the DLookup function. Note that the reference to the control isn't 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 varX As VariantvarX = DLookup("[CompanyName]", "Shippers", "[ShipperID] = " _ & Forms!Shippers!ShipperID)

The next example uses a variable, intSearch, to get the value.

Dim intSearch As Integer, varX As VariantintSearch = 1varX = DLookup("[CompanyName]", "Shippers", _ "[ShipperID] = " & intSearch)

Page 242: Microsoft Access Language

Microsoft Access Language Reference Página 242 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DMin, DMax Functions

Description

You can use the DMin and DMax functions to determine the minimum and maximum values in a specified set of records (a domain). Use the DMin and DMax functions in Visual Basic, a macro, a query expression, or a calculated control.

For example, you could use the DMin and DMax functions in calculated controls on a report to display the largest and smallest order amounts for a particular customer. Or you could use the DMin function 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 have the following arguments.

Argument Description

expr An 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. In expr, you can include the name of a field in a table, 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 A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

Page 243: Microsoft Access Language

Microsoft Access Language Reference Página 243 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The DMin and DMax functions return the minimum and maximum values that satisfy criteria. If expr identifies numeric data, the DMin and DMax functions return numeric values. If expr identifies string data, they return the string that is first or last alphabetically.

The DMin and DMax functions ignore Null values in the field referenced by expr. However, if no record satisfies criteria or if domain contains no records, the DMin and DMax functions return a Null.

Whether you use the DMin or DMax function in a macro, module, query expression, or calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use the DMin and DMax function 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 the DMin and DMax functions or the Min and Max functions in a calculated field expression in a totals query. If you use the DMin or DMax function, values are evaluated before the data is grouped. If you use the Min or Max function, the data is grouped before values in the field expression are evaluated.

Use the DMin or DMax function 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 the DMin or DMax function 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 the DMin or DMax function 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 aren't included when you use these functions. If you

criteria An optional string expression used to restrict the range of data on which the DMin or DMax function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DMin and DMax functions evaluate expr against the entire domain. Any field that is included in criteria must also be a field in domain, otherwise the DMin and DMax functions returns a Null.

Page 244: Microsoft Access Language

Microsoft Access Language Reference Página 244 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

want the DMax or DMin 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 by using the Update method.

See Also

Min, Max functions ("SQL Language Reference").

Example

The following 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 CurrencycurX = 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 isn't 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 CurrencycurX = 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 CurrencydteOrderDate = #3/30/95#curX = DMin("[Freight]", "Orders", _ "[OrderDate] = #" & dteOrderDate & "#")

DoCmd Object

Description

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.

Note The DoCmd object replaces the DoCmd statement from versions 1.x and 2.0 of Microsoft Access. The actions that were used as arguments for the DoCmd statement are now methods of the DoCmd object. For example, in Microsoft Access 2.0, you could have used the code DoCmd OpenForm "Orders" to open a form from Access Basic. In Microsoft Access 97, you would use the following syntax:

DoCmd.OpenForm "Orders"

Page 245: Microsoft Access Language

Microsoft Access Language Reference Página 245 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Syntax

[application.]DoCmd.method [arg1, arg2, ...]

The DoCmd object has the following arguments.

Remarks

Most of the methods of the DoCmd object have arguments some are required, while others are optional. If you omit optional arguments, the arguments assume the default values for the particular method. 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 doesn't support methods corresponding to the following actions:

l AddMenu.l MsgBox. Use the MsgBox function.l RunApp. Use the Shell function to run another application.l RunCode. Run the function directly in Visual Basic.l SendKeys. Use the SendKeys statement.l SetValue. Set the value directly in Visual Basic.l StopAllMacros.l StopMacro.

For more information on the Microsoft Access action corresponding to a DoCmd method, see the action topic.

Methods

ApplyFilter method, Beep method, CancelEvent method, Close method, CopyObject method,

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.

Page 246: Microsoft Access Language

Microsoft Access Language Reference Página 246 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DeleteObject method, DoMenuItem method, Echo method (DoCmd object), FindNext method, FindRecord method, GoToControl method, GoToPage method (DoCmd object), GoToRecord method, Hourglass method, Maximize method, Minimize method, MoveSize method, OpenForm method, OpenModule method, OpenQuery method, OpenReport method, OpenTable method, OutputTo method, PrintOut method, Quit method (DoCmd object), Rename method, RepaintObject method, Requery method (DoCmd object), Restore method, RunCommand method, RunMacro method, RunSQL method, Save method, SelectObject method, SendObject method, SetMenuItem method, SetWarnings method, ShowAllRecords method, ShowToolbar method, TransferDatabase method, TransferSpreadsheet method, TransferText method.

See Also

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

Example

The following example opens a form in Form view and moves to a new record.

Sub ShowNewRecord() DoCmd.OpenForm "Employees", acNormal DoCmd.GoToRecord , , acNewRecEnd Sub

DoMenuItem Action

Description

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

Note In Microsoft Access 97, the DoMenuItem action has been replaced by the RunCommand action. The DoMenuItem action is included in this version of Microsoft Access only for compatibility with previous versions. When you open and save a macro from a previous version of Microsoft Access that contains a DoMenuItem action, the action and its arguments will automatically be converted to the equivalent RunCommand action. The DoMenuItem action no longer appears in the list of actions in the Macro window in Microsoft Access 97.

When you convert a Microsoft Access database from a previous version of Microsoft Access, some commands may no longer be available. The command may have been renamed, moved to a different menu, or is no longer available in Microsoft Access 97. The DoMenuItem actions for such commands can't be converted to RunCommand actions. When you open the macro, Microsoft Access will display a RunCommand action with a blank Command argument for such commands. You must edit the macro and enter a valid RunCommand action, or delete the action.

You can use this action to do the following:

Page 247: Microsoft Access Language

Microsoft Access Language Reference Página 247 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l Carry out any Microsoft Access command from a macro. You must select a command that's 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.

l 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.

l 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 or global shortcut menu.

Setting

The DoMenuItem action has the following arguments.

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.

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

Action argument

Description

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

Menu Name The name of the menu that contains the command you want to carry out. This is a required argument.

Command The command you want to carry out. This is a required argument.

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

Page 248: Microsoft Access Language

Microsoft Access Language Reference Página 248 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

AddMenu action, DoMenuItem method, RunCommand action, SendKeys action.

DoMenuItem Method

Applies To

DoCmd object.

Description

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.

Note In Microsoft Access 97, the DoMenuItem method has been replaced by the RunCommand method. The DoMenuItem method is included in this version of Microsoft Access only for compatibility with previous versions. When you run existing Visual Basic code containing a DoMenuItem method, Microsoft Access will display the appropriate menu or toolbar command for Microsoft Access 97. However, unlike the DoMenuItem action in a macro, a DoMenuItem method in Visual Basic code isn't converted to a RunCommand method when you convert a database created in a previous version of Microsoft Access.

Some commands from previous versions of Microsoft Access aren't available in Microsoft Access 97, and DoMenuItem methods that run these commands will cause an error when they're executed in Visual Basic. You must edit your Visual Basic code to replace or delete occurrences of such DoMenuItem methods.

Syntax

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

The DoMenuItem method has the following arguments.

Argument Description

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

For other views, use the number of the view in the Menu Bar argument list, as shown in the Macro window in previous versions of Microsoft Access (count down the list, starting from 0).

Page 249: Microsoft Access Language

Microsoft Access Language Reference Página 249 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

menuname You can use one of the following intrinsic constants:

acFileacEditMenuacRecordsMenu

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

For other menus, use the number of the menu in the Menu Name argument list, as shown in the Macro window in previous versions of Microsoft Access (count down the list, starting from 0).

command You can use one of the following intrinsic constants:

acNewacSaveFormacSaveFormAsacSaveRecordacUndoacCutacCopyacPasteacDeleteacSelectRecordacSelectAllRecordsacObjectacRefresh

For other commands, use the number of the command in the Command argument list, as shown in the Macro window in previous versions of Microsoft Access (count down the list, starting from 0).

Page 250: Microsoft Access Language

Microsoft Access Language Reference Página 250 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

subcommand You can use one of the following intrinsic constants:

acObjectVerbacObjectUpdate

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, use the number of the subcommand in the Subcommand argument list, as shown in the Macro window in previous versions of Microsoft Access (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.

Page 251: Microsoft Access Language

Microsoft Access Language Reference Página 251 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The selections in the lists for the Menu Name, Command, and Subcommand action arguments in the Macro window depend on what you've 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.

See Also

AddMenu action, DoCmd object, DoMenuItem action, RunCommand method, SendKeys statement.

Example

The following example uses the DoMenuItem method to carry out the Paste command on the Edit menu in Form view in a Microsoft Access 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

DrawMode Property

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).

Note There is no acMenuVer80 setting for this argument. You can't use the DoMenuItem method to display Microsoft Access 97 commands (although existing DoMenuItem methods in Visual Basic code will still work). Use the RunCommand method instead.

Page 252: Microsoft Access Language

Microsoft Access Language Reference Página 252 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Report.

Description

You can use the DrawMode property to specify how the pen (the color used in drawing) interacts with existing background colors on a 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 color.

2 The inverse of setting 15 (NotMergePen).

3 The combination of the colors common to the background color and the inverse of the pen (MaskNotPen).

4 The inverse of setting 13 (NotCopyPen).

5 The combination of the colors common to both the pen and the inverse of the display (MaskPenNot).

6 The inverse of the display color (Invert).

7 The combination of the colors in the pen and in the display color, but not in both (XorPen).

8 The inverse of setting 9 (NotMaskPen).

9 The combination of the colors common to both the pen and the display (MaskPen).

Page 253: Microsoft Access Language

Microsoft Access Language Reference Página 253 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

The DrawMode property setting is an Integer value.

You can set the DrawMode property by using 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 appears on the report. For example, setting 7 uses the Xor operator to combine a draw-pattern pixel with a background pixel.

See Also

BackColor property, BackStyle property, Circle method, DrawStyle property, DrawWidth property, Event properties, FillColor property, FillStyle property, ForeColor property, Line method, PSet method.

DrawStyle Property

10 The inverse of setting 7 (NotXorPen).

11 No operation the output remains unchanged. In effect, this setting turns drawing off (Nop).

12 The combination of the display color and the inverse of the pen color (MergeNotPen).

13 (Default) The color specified by the ForeColor property (CopyPen).

14 The combination of the pen color and the inverse of the display color (MergePenNot).

15 The combination of the pen color and the display color (MergePen).

16 White pen color.

Page 254: Microsoft Access Language

Microsoft Access Language Reference Página 254 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Report.

Description

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.

The DrawStyle property setting has an Integer value.

You can set this property by using 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 3, the DrawStyle property settings 1 through 4 produce a solid line (the DrawStyle property value isn't changed).

See Also

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 line, transparent interior

6 Invisible line, solid interior

Page 255: Microsoft Access Language

Microsoft Access Language Reference Página 255 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

BackColor property, Circle method, DrawMode property, DrawWidth property, Event properties, FillColor property, FillStyle property, ForeColor property, Line method, PSet method.

DrawWidth Property

Applies To

Report.

Description

You can use the DrawWidth property to specify the line width for the Line, Circle, and PSet methods to print lines on reports.

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 by using 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 the DrawWidth property setting is greater than 3, DrawStyle property settings 1 through 4 produce a solid line (the DrawStyle property setting 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.

See Also

BackColor property, Circle method, DrawMode property, DrawStyle property, Event properties, FillColor property, FillStyle property, ForeColor property, Line method, PSet method.

Dropdown Method

Applies To

Combo Box control.

Description

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 control receives the focus during data entry.

Page 256: Microsoft Access Language

Microsoft Access Language Reference Página 256 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Syntax

combobox.Dropdown

The Dropdown method has the following argument.

Remarks

If the specified combo box control doesn't have the focus, an error occurs. The use of this method is identical to pressing the F4 key when the control has the focus.

Example

The following example shows how you can use the Dropdown method within the GotFocus event procedure to force a combo box named SupplierID to drop down when it receives the focus.

Private Sub SupplierID_GotFocus() Me!SupplierID.DropdownEnd Sub

DStDev, DStDevP Functions

Description

You can use the DStDev and DStDevP functions to estimate the standard deviation across a set of values in a specified set of records (a domain). Use the DStDev and DStDevP functions in Visual Basic, a macro, a query expression, or a calculated control on a form or report.

Use the DStDevP function to evaluate a population, and the DStDev function 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 have the following arguments.

Argument Description

combobox A combo box control on a form.

Page 257: Microsoft Access Language

Microsoft Access Language Reference Página 257 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If domain refers to fewer than two records or if fewer than two records satisfy criteria, the DStDev and DStDevP functions return a Null, indicating that a standard deviation can't be calculated.

Whether you use the DStDev or DStDevP function in a macro, module, query expression, or calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use the DStDev and DStDevP functions 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:

Argument Description

expr An 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. In expr, you can include the name of a field in a table, 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 A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria An optional string expression used to restrict the range of data on which the DStDev or DStDevP function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DStDev and DStDevP functions evaluate expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise, the DStDev and DStDevP functions will return a Null.

Page 258: Microsoft Access Language

Microsoft Access Language Reference Página 258 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

>(DStDev("[Freight]", "Orders") + DAvg("[Freight]", "Orders"))

You can use the DStDev and DStDevP functions within a calculated field expression in a query, or in the Update To row of an update query.

Note You can use the DStDev and DStDevP functions or the StDev and StDevP functions in a calculated field expression in a totals query. If you use the DStDev or DStDevP function, values are calculated before data is grouped. If you use the StDev or StDevP function, the data is grouped before values in the field expression are evaluated.

Use the DStDev and DStDevP function 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, the DStDev and DStDevP functions return a Double data type. If you use the DStDev or DStDevP function 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 clicking Save Record on the File menu, moving the focus to another record, or by using the Update method.

Example

The following 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 by 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 DoublestrCountry = "UK"dblX = DStDev("[Freight]", "Orders", _ "[ShipCountry] = '" & strCountry & "'")dblY = DStDevP("[Freight]", "Orders", _ "[ShipCountry] = '" & strCountry & "'")

DSum Function

Page 259: Microsoft Access Language

Microsoft Access Language Reference Página 259 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the DSum functions to calculate the sum of a set of values in a specified set of records (a domain). Use the DSum function in Visual Basic, a macro, a query expression, or a calculated control.

For example, you could use the DSum function 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 the DSum function in a calculated control to display a running sum of sales for a particular product.

Syntax

DSum(expr, domain[, criteria])

The DSum function has the following arguments.

Argument Description

expr An expression that identifies the numeric field whose values you want to total. 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. In expr, you can include the name of a field in a table, 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 A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria An optional string expression used to restrict the range of data on which the DSum function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DSum function evaluates expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise, the DSum function returns a Null.

Page 260: Microsoft Access Language

Microsoft Access Language Reference Página 260 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If no record satisfies the criteria argument or if domain contains no records, the DSum function returns a Null.

Whether you use the DSum function in a macro, module, query expression, or calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use the DSum function 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 the DSum or Sum function in a calculated field expression in a totals query. If you use the DSum function, values are calculated before data is grouped. If you use the Sum function, the data is grouped before values in the field expression are evaluated.

You may want to use the DSum function 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 that displays information about a particular product. You could use the DSum function 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 the DSum function to maintain a running sum on a form.

Note Unsaved changes to records in domain aren't 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 clicking Save Record on the File menu, moving the focus to another record, or by using the Update method.

See Also

DCount function, RunningSum property, Sum function ("SQL Language Reference").

Example

The following 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 CurrencycurX = DSum("[Freight]", "Orders", "[ShipCountry] = 'UK'")

The next example calculates a total by 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 CurrencycurX = 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 example, 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

Page 261: Microsoft Access Language

Microsoft Access Language Reference Página 261 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

update the records. Create a new query based on the Products table, and click Update on 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

Description

You can use the DVar and DVarP functions to estimate variance across a set of values in a specified set of records (a domain). Use the DVar and DVarP functions in Visual Basic, a macro, a query expression, or a calculated control on a form or report.

Use the DVarP function to evaluate variance across a population, and the DVar function 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 have the following arguments.

Argument Description

expr An 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. In expr, you can include the name field in a table, 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.

Page 262: Microsoft Access Language

Microsoft Access Language Reference Página 262 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If domain refers to fewer than two records or if fewer than two records satisfy criteria, the DVar and DVarP functions return a Null, indicating that a variance can't be calculated.

Whether you use the DVar or DVarP function in a macro, module, query expression, or calculated control, you must construct the criteria argument carefully to ensure that it will be evaluated correctly.

You can use the DVar and DVarP function 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 the DVar and DVarP functions or the Var and VarP functions in a calculated field expression in a totals query. If you use the DVar or DVarP function, values are calculated before data is grouped. If you use the Var or VarP function, the data is grouped before values in the field expression are evaluated.

Use the DVar and DVarP functions 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 clicking Save Record on the File menu, moving the focus to another record, or by using the Update method.

Example

domain A string expression identifying the set of records that constitutes the domain. It can be a table name or a query name.

criteria An optional string expression used to restrict the range of data on which the DVar or DVarP function is performed. For example, criteria is often equivalent to the WHERE clause in an SQL expression, without the word WHERE. If criteria is omitted, the DVar and DVarP functions evaluate expr against the entire domain. Any field that is included in criteria must also be a field in domain; otherwise the DVar and DVarP functions return a Null.

Page 263: Microsoft Access Language

Microsoft Access Language Reference Página 263 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The following 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 by 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 DoublestrCountry = "UK"dblX = DVar("[Freight]", "Orders", "[ShipCountry] = '" _ & strCountry & "'")

Echo Action

Description

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 has the following arguments.

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

Action argument

Description

Echo On Click Yes (turn echo on) or No (turn echo off) in the Echo On box in the Action Arguments section of the Macro window. 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."

Page 264: Microsoft Access Language

Microsoft Access Language Reference Página 264 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

updating the screen. When the macro finishes, Microsoft Access automatically turns echo back on and repaints the window. The No setting for the Echo On argument 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 icon (or whatever mouse pointer icon you've 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.

See Also

Echo method (DoCmd object), SetWarnings action.

Echo Method (Application Object)

Applies To

Application object.

Description

The Echo method specifies whether Microsoft Access repaints the display screen.

Syntax

Application.Echo echoon[, statusbartext]

The Echo method has the following arguments.

Argument Description

echoon True (default) indicates that the screen is repainted; False indicates that the screen isn't repainted.

Page 265: Microsoft Access Language

Microsoft Access Language Reference Página 265 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 won't 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 repainting on or off. The Repaint method forces an immediate screen repainting.

See Also

Echo action, Echo method (DoCmd object).

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 icon to indicate that processing is taking place, and the screen isn't repainted. When this task is completed, the hourglass changes back to a pointer and screen repainting is turned back on.

Sub EchoOff() Application.Echo False DoCmd.Hourglass True DoCmd.OpenForm "Employees", acNormal DoCmd.Minimize Application.Echo True DoCmd.Hourglass FalseEnd Sub

Echo Method (DoCmd Object)

Applies To

statusbartext A string expression that specifies the text to display in the status bar when repainting is turned on or off.

Page 266: Microsoft Access Language

Microsoft Access Language Reference Página 266 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DoCmd object.

Description

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 has the following arguments.

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's recommended that you use the existing Echo method of the Application object instead.

See Also

Application object, DoCmd object, Echo action, Echo method (Application object), SetWarnings method.

Example

The following 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."

Argument Description

echoon Use True (–1) to turn echo on and False (0) to turn it off.

statusbartext A string expression.

Page 267: Microsoft Access Language

Microsoft Access Language Reference Página 267 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Enabled, Locked Properties

Applies To

Enabled property ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Page, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Locked property ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, List Box control, Option Button control, Option Group control, Subform/Subreport control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

l The Enabled property specifies whether a control can have the focus in Form view.l The Locked property specifies whether you can edit data in a control in Form view.

Setting

The Enabled property uses the following settings.

The Locked 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)

Page 268: Microsoft Access Language

Microsoft Access Language Reference Página 268 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set these properties by using a form'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 to only 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.

Setting Description Visual Basic

Yes (Default for unbound object frames) The control functions normally but doesn't allow editing, adding, or deleting data.

True

No (Default for all controls except unbound object frames) The control functions normally and allows editing, adding, and deleting data.

False

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.

Page 269: Microsoft Access Language

Microsoft Access Language Reference Página 269 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 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.

See Also

AllowEdits property, DisplayWhen property, SetValue action, TabStop property, Visible property.

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 IfEnd Sub

Enter, Exit Events

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Subform/Subreport control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

l The Enter event occurs before a control actually receives the focus from a control on the same form.

l The Exit event occurs just before a control loses the focus to another control on the same form.

No No The control can't have the focus. Control and data are disabled (dimmed).

Page 270: Microsoft Access Language

Microsoft Access Language Reference Página 270 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Notes

l The Enter and Exit events apply only to controls on a form, not controls on a report.l 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

To run a macro or event procedure when these events occur, set the OnEnter or OnExit property to the name of the macro or to [Event Procedure].

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, or giving instructions on how to use the control.

The Enter event occurs before the GotFocus event. The Exit event occurs before the LostFocus event.

Unlike the GotFocus and LostFocus events, 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 Enter and GotFocus 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 to a control on a form, and that control doesn't have the focus on that form, the Exit and LostFocus events for the control that does have the focus on the 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 (a control that doesn't already have the focus on the subform), 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)

Page 271: Microsoft Access Language

Microsoft Access Language Reference Página 271 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

BeforeUpdate, AfterUpdate events, Event properties, GotFocus, LostFocus events.

Enter, Exit Events Event Procedures

Description

To create an event procedure that runs 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 has the following argument.

The Exit event procedure has the following arguments.

Argument Description

controlname The name of the control whose Enter event procedure you want to run.

Page 272: Microsoft Access Language

Microsoft Access Language Reference Página 272 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can't cancel the Enter event.

See Also

Enter, Exit events — macros.

Example

In the following 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 clicks the Cancel button, the Cancel argument is set to True (–1), which moves the focus to the text box without saving changes. If the user chooses the OK button, the changes are saved, and the focus moves to another control.

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

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 IfEnd Sub

Enter, Exit Events Macros

Description

Argument Description

controlname The name of the control whose Exit event procedure you want to run.

Cancel The setting determines if the Exit event occurs. Setting the Cancel argument to True (–1) cancels the Exit event

Page 273: Microsoft Access Language

Microsoft Access Language Reference Página 273 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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, you can ensure that the focus doesn'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 to cancel the Enter event. However, you can use the GoToControl action in an Enter macro to move the focus to a different control.

See Also

Enter, Exit events — event procedures.

EnterKeyBehavior Property

Applies To

Text Box control.

Description

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 this 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 under Move After Enter 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)

Page 274: Microsoft Access Language

Microsoft Access Language Reference Página 274 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using a form's property sheet, a macro, or Visual Basic.

You can set the default for this property by using the control's default control style or the DefaultControl method in Visual Basic.

Remarks

The following options are available under Move After Enter on the Keyboard tab of the Options dialog box.

See Also

AutoTab property.

Error Event

Applies To

Form, Report.

Description

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.

New Line In Field

Pressing ENTER in the control creates a new line in the control so you can enter additional text.

True (–1)

Option 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.

Page 275: Microsoft Access Language

Microsoft Access Language Reference Página 275 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

To run a macro or event procedure when this event occurs, set the OnError property to the name of the macro or to [Event Procedure].

By running an event procedure or 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.

See Also

Err object, Error function, Event properties.

Error Event Event Procedures

Description

To create an event procedure that runs 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 has 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.

Page 276: Microsoft Access Language

Microsoft Access Language Reference Página 276 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can't cancel the Error event.

See Also

Error event — macros.

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.

To try the example, add the following event procedure to a form that is based on a table with a unique employee ID number as the key for each record.

Private Sub Form_Error(DataErr As Integer, Response As Integer) Const conDuplicateKey = 3022 Dim strMsg As String

If DataErr = conDuplicateKey Then Response = acDataErrContinue

Response The setting determines whether or not an error message is displayed. The Response argument can be one of the following intrinsic 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.

Page 277: Microsoft Access Language

Microsoft Access Language Reference Página 277 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

strMsg = "Each employee record must have a unique " _ & "employee ID number. Please recheck your data." MsgBox strMsg End IfEnd Sub

Error Event Macros

Description

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.

See Also

Error event — event procedures.

Eval Function

Description

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 argument must evaluate to a string or numeric value; it can't evaluate to a Microsoft Access object.

Note If you are passing the name of a function to the Eval function, you must include parentheses after the name of the function in the stringexpr argument. For example:

Page 278: Microsoft Access Language

Microsoft Access Language Reference Página 278 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Debug.Print Eval("ShowNames()") ' ShowNames is user-defined

' function.

Debug.Print Eval("StrComp(""Joe"",""joe"", 1)")

Debug.Print Eval("Date()")

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 doesn't contain a 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 StringSet ctl = Forms!Employees!LastNamestrCtl = "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 can't 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 a 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 a string within another string.

Dim intState As IntegerintState = Eval("Forms!Orders!ShipRegion In " _ & "('AK', 'CA', 'ID', 'WA', 'MT', 'NM', 'OR')")

See Also

Choose function, IIf function, Switch 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 intIEnd Sub

Page 279: Microsoft Access Language

Microsoft Access Language Reference Página 279 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 doesn't 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!HelpButtonIf (Left(ctl.OnClick, 1) = "=") Then varTemp = Eval(Mid(ctl.OnClick,2))Else DoCmd.RunMacro ctl.OnClickEnd If

Event Properties

Applies To

Event Properties and Objects They Apply To.

Description

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.

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, in a macro, or by using 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. To use them, click the Build button to the right of the property box, or right-click the property box and then click Build on the shortcut menu. In the Choose Builder dialog box, select:

l 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.

l 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.

Page 280: Microsoft Access Language

Microsoft Access Language Reference Página 280 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l 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.

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.

Private Sub Country_AfterUpdate() If Country = "Canada" Then [Print Country Report].OnClick = "PrintCanadaReport" ElseIf Country = "USA" Then [Print Country Report].OnClick = "PrintUSAReport" End IfEnd Sub

Event Properties and Objects They Apply To

Description

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 property Applies to

AfterDelConfirm Forms.

AfterInsert Forms.

Page 281: Microsoft Access Language

Microsoft Access Language Reference Página 281 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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, tab, text box) on a form.

OnClick* Forms. Form sections. Controls (bound object frame, chart, check box, combo box, command button, image, label, list box, option button, option group, rectangle, tab, 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, image, label, list box, option button, option group, rectangle, tab, text box, toggle button, unbound object frame) on a form.

Page 282: Microsoft Access Language

Microsoft Access Language Reference Página 282 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

OnDeactivate Forms and reports.

OnDelete Forms.

OnEnter* Controls (ActiveX, bound object frame, chart, check box, combo box, command button, list box, option button, option group, subform/subreport, tab, text box, toggle button, unbound object frame) on a form.

OnError Forms and reports.

OnExit* Controls (ActiveX, bound object frame, chart, check box, combo box, command button, list box, option button, option group, subform/subreport, tab, text box, toggle button, unbound object frame) on a form.

OnFilter Forms.

OnFormat Report sections.

Event property

Applies to

OnGotFocus Forms. Controls (ActiveX, bound object frame, check box, combo box, command button, list box, option button, tab, 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, tab, text box, toggle button, unbound object frame) on a form.

Page 283: Microsoft Access Language

Microsoft Access Language Reference Página 283 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

OnKeyPress Forms. Controls (bound object frame, check box, combo box, command button, list box, option button, tab, 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, tab, text box, toggle button, unbound object frame) on a form.

OnLoad Forms.

OnLostFocus Forms. Controls (ActiveX, bound object frame, check box, combo box, command button, list box, option button, tab, 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, image, label, list box, option button, option group, rectangle, tab, 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, image, label, list box, option button, option group, rectangle, tab, 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, tab, text box, toggle button, unbound object frame) on a form.

OnNoData Reports.

Page 284: Microsoft Access Language

Microsoft Access Language Reference Página 284 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

* 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.

EventProcPrefix Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form section, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Page, Page Break control, Rectangle control, Report section, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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

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 (ActiveX, bound object frame, unbound object frame) on a form.

Page 285: Microsoft Access Language

Microsoft Access Language Reference Página 285 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The EventProcPrefix property setting is a string expression.

This property is available only by using a macro or Visual Basic and is read-only in all views.

Remarks

Microsoft Access adds the prefix portion of an event procedure name to the event name with an underscore character ( _ ).

Exit Event

See Enter, Exit Events.

FailOnError Property

Applies To

Action query.

Description

You can use the FailOnError property to specify whether an update or delete query that is run against an ODBC data source will terminate if an error occurs. The FailOnError property lets you optimize bulk update queries run against ODBC data sources so that they are executed on the server if the partial-failure behavior of the Microsoft Jet database engine isn't desired.

Note The FailOnError property applies only to update and delete queries.

Setting

The FailOnError property uses the following settings.

You can set the FailOnError property by using the query's property sheet or Visual Basic. To set this property with Visual Basic, you must first add it to a QueryDef object's Properties collection

Setting Description Visual Basic

Yes Errors terminate the query. True (–1)

No (Default) Errors don't terminate the query.

False (0)

Page 286: Microsoft Access Language

Microsoft Access Language Reference Página 286 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

by using the CreateProperty method.

Remarks

When the FailOnError property is set to Yes and the query executes against a single table on an ODBC database and doesn't contain expressions that can't be evaluated on the server, the query will be sent to the server to be executed. When the FailOnError property is set to Yes, if an error occurs during a delete or update, the query stops executing and the table is rolled back to its original state. In all other cases, the FailOnError property will be treated as if it were set to No. When the FailOnError property is set to No and an error occurs, you can accept the query results or roll back any changes.

When the FailOnError property is set to No and the query executes against local data, update or delete queries operate just as they did in previous versions of Microsoft Access; when the query affects multiple rows, some rows may be updated and others may fail due to errors. If an error occurs, you are notified of the reason for the error and the number of records affected, and you can accept the query results or roll back any changes.

Setting this property to Yes is the same as using the dbFailOnError intrinsic constant of the DAO Execute method.

FastLaserPrinting Property

Applies To

Form, Report.

Description

You can use the FastLaserPrinting property to specify whether lines and rectangles are replaced by text character lines — similar to the underscore ( _ ) and vertical bar (|) characters — when you print a form or report using most laser printers. Replacing lines and rectangles with text character lines can make printing much faster.

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)

Page 287: Microsoft Access Language

Microsoft Access Language Reference Página 287 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using a form's or report's property sheet, a macro, or Visual Basic.

Remarks

The FastLaserPrinting property affects any line or rectangle on a form or report, including controls that have these shapes (for example, a border around a text box).

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.

Example

The following example shows how to set the FastLaserPrinting property for the Invoice report while in report Design view:

DoCmd.OpenReport "Invoice", acDesignReports!Invoice.FastLaserPrinting = TrueDoCmd.Close acReport, "Invoice", acSaveYes

FieldName Property

Applies To

Table field.

Description

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 by using Visual Basic.

In Visual Basic, use the DAO 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

Page 288: Microsoft Access Language

Microsoft Access Language Reference Página 288 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

statements.

See Also

Caption property, Name property ("DAO Language Reference").

FieldSize Property

Applies To

Table field.

Description

You can use the FieldSize property to set the maximum size for data stored in a field set to the Text, Number, or AutoNumber 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 AutoNumber, the FieldSize property can be set to Long Integer or Replication ID.

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

Page 289: Microsoft Access Language

Microsoft Access Language Reference Página 289 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

You can set this property only from the table's property sheet.

To set the size of a field from Visual Basic, use the DAO Size property to read and set the maximum size of Text fields (for data types other than Text, the DAO 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 Default Field Sizes 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. For example, if you change the FieldSize setting for a Text data type field from 255 to 50, data beyond the new 50-character setting 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 a Single to an

Single Stores numbers from–3.402823E38 to–1.401298E–45 for negative values and from1.401298E–45 to 3.402823E38 for positive values.

7 4 bytes

Double Stores numbers from–1.79769313486231E308 to–4.94065645841247E–324 for negative values and from 1.79769313486231E308 to 4.94065645841247E–324 for positive values.

15 8 bytes

Replication ID

Globally unique identifier (GUID)

N/A 16 bytes

Page 290: Microsoft Access Language

Microsoft Access Language Reference Página 290 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Integer field size, 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 data that result from a change to the FieldSize property after saving those changes 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.

See Also

DecimalPlaces property, FieldSize property ("DAO Language Reference"), Size property ("DAO Language Reference").

FillColor Property

Applies To

Report.

Description

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 or preview the reports on a color monitor.

Setting

The FillColor property contains a numeric expression that specifies the fill color for all boxes and circles.

You can set this property only by using a macro or a Visual Basic event procedure specified by a section's OnPrint event property.

You can use the RGB or QBColor functions to set this property. The FillColor property setting has a data type of Long.

See Also

Circle method, DrawMode property, DrawStyle property, DrawWidth property, FillStyle property, Line method, PSet method, QBColor function, RGB function.

Example

The following example uses the Circle method to draw a circle and create a pie slice within the circle. Then it uses the FillColor and FillStyle properties to color the pie slice red. It also draws a line from the upper left to the center of the circle.

Page 291: Microsoft Access Language

Microsoft Access Language Reference Página 291 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To try this example in Microsoft Access, create a new report. 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

' Draw line to center of circle. Dim intColor As Integer Dim sngTop As Single, sngLeft As Single Dim sngWidth As Single, sngHeight As Single

Me.ScaleMode = 3 ' Set scale to pixels. sngTop = Me.ScaleTop ' Top inside edge. sngLeft = Me.ScaleLeft ' Left inside edge. sngWidth = Me.ScaleWidth / 2 ' Width inside edge. sngHeight = Me.ScaleHeight / 2 ' Height inside edge. intColor = RGB(255, 0, 0) ' Make color red.

' Draw line. Me.Line (sngTop, sngLeft)-(sngWidth, sngHeight), intColorEnd Sub

FillStyle Property

Applies To

Report.

Description

You can use the FillStyle property to specify whether a circle or line drawn by the Circle or Line method on a report is transparent, opaque, or filled with a pattern.

Setting

The FillStyle property uses the following settings.

Page 292: Microsoft Access Language

Microsoft Access Language Reference Página 292 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the FillStyle property by using a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

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.

See Also

BorderColor property, BorderStyle property, BorderWidth property, Circle method, Event properties, FillColor property, Line method, Print event.

Example

See the FillColor property example.

Setting Description

0 Opaque

1 (Default) Transparent

2 Horizontal Line

3 Vertical Line

4 Upward Diagonal

5 Downward Diagonal

6 Cross

7 Diagonal Cross

Page 293: Microsoft Access Language

Microsoft Access Language Reference Página 293 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Filter Event

Applies To

Form.

Description

The Filter event occurs when the user does one of the following:

l On the Records menu in Form view, points to Filter and then clicks Filter By Form, 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.

l On the Records menu in Form view, points to Filter and then clicks Advanced Filter/Sort. This opens the Advanced Filter/Sort window, where you can create complex filters for the form.

l Clicks Advanced Filter/Sort on the Filter menu while the Filter By Form window is open, or clicks Filter By Form on the Filter menu while the Advanced Filter/Sort window is open. This causes the ApplyFilter event to occur when the open filter window is closed, and then the Filter event to occur when the other filter window is opened.

Remarks

To run a macro or event procedure when this event occurs, set the OnFilter property to the name of the macro or to [Event Procedure].

You can use the Filter event to:

l 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 don't 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

l 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.

l If the return value of the GetOption method is assigned to a variable, the variable must be declared as a Variant.

l If your database may run on a version of Microsoft Access for a language other than the one in which you created it, then you must supply the arguments for the GetOption and SetOption methods in English.

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.

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

Page 294: Microsoft Access Language

Microsoft Access Language Reference Página 294 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 Dim 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 IfEnd Sub

GotFocus, LostFocus Events

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, List Box control, Option Button control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

l The GotFocus event occurs when a form or control receives the focus.l The LostFocus event occurs when a form or control loses the focus.

Note The GotFocus and LostFocus events apply only to forms and controls on a form, not controls on a report.

Remarks

To run a macro or event procedure when these events occur, set the OnGotFocus, or OnLostFocus property to the name of the macro or to [Event Procedure].

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 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

Page 295: Microsoft Access Language

Microsoft Access Language Reference Página 295 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

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.

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 to a control on a form, and that control doesn't have the focus on that form, the Exit and LostFocus events for the control that does have the focus on the 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

Page 296: Microsoft Access Language

Microsoft Access Language Reference Página 296 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Activate, Deactivate events, ActiveControl property, ActiveForm property, Enabled, Locked properties, Enter, Exit events, Event properties, GoToControl action, Open, Close events, SelectObject action, SetFocus method, Visible property.

GotFocus, LostFocus Events — Event Procedures

Description

To create an event procedure that runs 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 have the following argument.

Remarks

Argument Description

controlname The name of the control whose GotFocus or LostFocus event procedure you want to run.

Page 297: Microsoft Access Language

Microsoft Access Language Reference Página 297 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

GotFocus, LostFocus events — macros.

Example

The following example displays a message in a label when the focus moves to an option button.

To try the example, add the following event procedures to a form named 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

Description

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.

See Also

GotFocus, LostFocus events — event procedures.

Page 298: Microsoft Access Language

Microsoft Access Language Reference Página 298 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

GoToControl Action

Description

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 has the following argument.

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.

See Also

GoToControl method, GoToPage action, GoToRecord action, SelectObject action, SetFocus method.

Action argument

Description

Control Name The name of the field or control where you want the focus. Enter the field or control name in the Control Name box in the Action Arguments section of the Macro window. 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].

Page 299: Microsoft Access Language

Microsoft Access Language Reference Página 299 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

GoToControl Method

Applies To

DoCmd object.

Description

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 has the following argument.

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 ControlSet ctl = Forms!Form1!Field3DoCmd.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.

See Also

GoToControl action, GoToPage method (DoCmd object), GoToRecord method, SelectObject method, SetFocus method.

Example

The following example uses the GoToControl method to move the focus to the EmployeeID field:

Argument Description

controlname A string expression that's the name of a control on the active form or datasheet.

Page 300: Microsoft Access Language

Microsoft Access Language Reference Página 300 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DoCmd.GoToControl "EmployeeID"

GoToPage Action

Description

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've 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. You can also present multiple pages of information on a single form by using tab controls.

Setting

The GoToPage action has the following arguments.

Note The Right and Down arguments are in inches or centimeters, depending on the units set for

Action argument

Description

Page Number The number of the page to which you want to move the focus. Enter the page number in the Page Number box in the Action Arguments section of the Macro window. 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 horizontal position of the spot on the page, measured from the left edge of its containing window, that's to appear at the left edge of the window. This is required if you specify a Down argument.

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

Page 301: Microsoft Access Language

Microsoft Access Language Reference Página 301 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Measurement System on the Number tab of the Regional Settings Properties dialog box in 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. Microsoft Access displays the part of the page whose upper-left corner is offset the specified distance from the upper-left corner of the page.

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.

See Also

Cycle property, GoToControl action, GoToPage Method (DoCmd object), GoToRecord action, SelectObject action.

GoToPage Method (DoCmd Object)

Applies To

DoCmd object.

Description

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 has the following arguments.

Argument Description

Page 302: Microsoft Access Language

Microsoft Access Language Reference Página 302 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The units for the right and down arguments are expressed in 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 95. It's recommended that you use the existing GoToPage method of the Form object instead.

See Also

DoCmd object, GoToControl method, GoToPage action, GoToPage method (Form object), GoToRecord method, SelectObject method, SetFocus method.

Example

The following 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

GoToPage Method (Form Object)

Applies To

Form object.

Description

The GoToPage method moves the focus to the first control on a specified page in the active

pagenumber A numeric expression that's 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's a valid horizontal offset for the page.

down A numeric expression that's a valid vertical offset for the page.

Page 303: Microsoft Access Language

Microsoft Access Language Reference Página 303 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

form.

Syntax

form.GoToPage pagenumber[, right, down]

The GoToPage method has the following arguments.

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've 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 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 that's offset from the upper-left corner of the window by the distance specified in the right and down arguments.

See Also

GoToPage action, GoToPage method (DoCmd object).

Argument Description

form A Form object that represents the active form.

pagenumber A numeric expression that's a valid page number for the active form.

right A numeric expression that's 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's a valid vertical offset (in twips) from the top of the window to the part of the page to be viewed.

Page 304: Microsoft Access Language

Microsoft Access Language Reference Página 304 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

GoToRecord Action

Description

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

Setting

The GoToRecord action has the following arguments.

(continued)

Action argument

Description

Object Type The type of object that contains the record you want to make current. Click Table, Query, or Form in 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 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 by the Object Type argument. If you leave the Object Type argument blank, leave this argument blank also.

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

Page 305: Microsoft Access Language

Microsoft Access Language Reference Página 305 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 clicking Go To on the Edit menu. The First, Last, Next, Previous, and New Record 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 by 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.

See Also

GoToControl action, GoToPage action, GoToRecord method, SelectObject action.

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

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

l 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 window.

Note If you use the First, Last, or New setting for the Record argument, Microsoft Access ignores the Offset argument. If you enter an Offset argument that's too large, Microsoft Access displays an error message. You can't enter negative numbers for the Offset argument.

Page 306: Microsoft Access Language

Microsoft Access Language Reference Página 306 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

GoToRecord Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Argument Description

objecttype One of the following intrinsic constants:

acActiveDataObject (default)acDataFormacDataQueryacDataTable

objectname A string expression that's the valid name of an object of the type selected by the objecttype argument.

record One of the following intrinsic constants:

acFirstacGoToacLastacNewRecacNext (default)acPrevious

Page 307: Microsoft Access Language

Microsoft Access Language Reference Página 307 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If you leave the objecttype and objectname arguments blank (the default constant, acActiveDataObject, is assumed for objecttype), 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.

See Also

DoCmd object, GoToControl method, GoToPage method (DoCmd object), GoToRecord action, SelectObject method.

Example

The following example uses the GoToRecord method to make the seventh record in the form Employees current:

DoCmd.GoToRecord acDataForm, "Employees", acGoTo, 7

GridX, GridY Properties

Applies To

Form, Report.

Description

You can use the GridX and GridY properties to specify the horizontal and vertical divisions of the alignment grid in form Design view and report Design view.

Setting

Enter an integer between 1 and 64 representing the number of subdivisions per unit of

If you leave this argument blank, the default constant (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.

Page 308: Microsoft Access Language

Microsoft Access Language Reference Página 308 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

measurement. If the Measurement System box is set to U.S. on the Number tab of the Regional Settings Properties dialog box of Windows Control Panel, the default setting is 24 for the GridX property (horizontal) and 24 for the GridY property (vertical).

You can set this property by using the property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property by 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 (although the grid lines are still displayed).

GroupHeader, GroupFooter Properties

Applies To

Report.

Description

You can use the GroupHeader and GroupFooter properties to create a group header or a group footer for a selected field or expression in a report. You can use group headers and footers to label or summarize data in a group of records. For example, if you set the GroupHeader property to Yes for the Categories field, each group of products will begin with its category name.

Setting

The GroupHeader and GroupFooter properties use the following settings.

You set these properties in the Sorting And Grouping box.

You can set these properties 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.

Setting Description

Yes Creates a group header or footer.

No (Default) Doesn't create a group header or footer.

Page 309: Microsoft Access Language

Microsoft Access Language Reference Página 309 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

To set the grouping properties — GroupOn, GroupInterval, and KeepTogether — to other than their default values, you must first set the GroupHeader or GroupFooter property or both to Yes for the selected field or expression.

See Also

CreateGroupLevel function, GroupInterval property, GroupLevel property, GroupOn property, KeepTogether property — groups, SortOrder property.

GroupInterval Property

Applies To

Report.

Description

You can use the GroupInterval property with the GroupOn property to specify how records are grouped in a report. The GroupInterval property specifies an interval value that records are grouped by. This interval differs depending on the data type and GroupOn property setting of 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 Text field, such as ProductName.

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 by using the 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) Set to 1.

Page 310: Microsoft Access Language

Microsoft Access Language Reference Página 310 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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.

See Also

CreateGroupLevel function, GroupHeader, GroupFooter properties, GroupLevel property, GroupOn property, KeepTogether property — groups, SortOrder property.

Example

The following example sets the SortOrder and grouping properties for the first group level in the Products By Category report to create an alphabetical list of products.

Private Sub Report_Open(Cancel As Integer) ' Set SortOrder property to ascending order. Me.GroupLevel(0).SortOrder = False ' Set GroupOn property. Me.GroupLevel(0).GroupOn = 1 ' Set GroupInterval property to 1. Me.GroupLevel(0).GroupInterval = 1 ' Set KeepTogether property to With First Detail. Me.GroupLevel(0).KeepTogether = 2End Sub

GroupLevel Property

Applies To

Report.

Description

You can use the GroupLevel property in Visual Basic to refer to the group level you are grouping

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.

Page 311: Microsoft Access Language

Microsoft Access Language Reference Página 311 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

or sorting on in a report.

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.

You can use this property only by using Visual Basic 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 by using the CreateGroupLevel function.

If a group is already defined for a report (the GroupLevel property is set to 0), then you can use the ControlSource property to change the group level in the report's Open event procedure. For example, the following code changes the ControlSource property to a value contained in the txtPromptYou text box on the open form named SortForm:

Private Sub Report_Open(Cancel As Integer) Me.GroupLevel(0).ControlSource _ = Forms!SortForm!txtPromptYouEnd Sub

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.

Page 312: Microsoft Access Language

Microsoft Access Language Reference Página 312 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

ControlSource property, CreateGroupLevel function, GroupInterval property, GroupOn property, KeepTogether Property — Groups, SortOrder property.

Example

See the GroupInterval property example.

GroupOn Property

Applies To

Report.

Description

You can use the GroupOn property in a report 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

Page 313: Microsoft Access Language

Microsoft Access Language Reference Página 313 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the GroupOn property by using the Sorting And Grouping box, a macro, or Visual Basic.

In 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.

See Also

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

Page 314: Microsoft Access Language

Microsoft Access Language Reference Página 314 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

CreateGroupLevel function, GroupHeader, GroupFooter properties, GroupInterval property, GroupLevel property, KeepTogether property — groups, SortOrder property.

GrpKeepTogether Property

Applies To

Report.

Description

You can use the GrpKeepTogether property to specify whether groups in a multiple column report that have their KeepTogether property for a group 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.

You can set the GrpKeepTogether property by using the report's property sheet, a macro, or Visual Basic.

This property can be set only in report Design view.

Remarks

You can use this property to 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.

The GrpKeepTogether property setting has no effect if the KeepTogether property for a group is set to No.

See Also

GroupInterval property, GroupOn property, KeepTogether property — groups, KeepTogether

Setting Description Visual Basic

Per Page Groups are kept together by page.

0

Per Column

(Default) Groups are kept together by column.

1

Page 315: Microsoft Access Language

Microsoft Access Language Reference Página 315 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

property — sections.

GUID Property

Applies To

Reference object.

Description

The GUID property of a Reference object returns a GUID that identifies a type library in the Windows Registry.

Setting

The GUID property is available only by using Visual Basic and is read-only.

Remarks

Every type library has an associated GUID which is stored in the Registry. When you set a reference to a type library, Microsoft Access uses the type library's GUID to identify the type library.

You can use the AddFromGUID method to create a Reference object from a type library's GUID.

See Also

AddFromGUID method, GUIDFromString function, StringFromGUID function.

Example

See the FullPath property example.

GUIDFromString Function

Description

The GUIDFromString function converts a string to a GUID, which is an array of type Byte.

Syntax

GUIDFromString(stringexpression)

The GUIDFromString function has the following argument.

Page 316: Microsoft Access Language

Microsoft Access Language Reference Página 316 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The Microsoft Jet database engine stores GUIDs as arrays of type Byte. However, Microsoft Access can't return Byte data from a control on a form or report. In order to return the value of a GUID from a control, you must convert it to a string. To convert a GUID to a string, use the StringFromGUID function. To convert a string to a GUID, use the GUIDFromString function.

See Also

StringFromGUID function.

Example

The following example uses the GUIDFromString function to convert a string to a GUID. The string is a GUID stored in string form in a replicated Employees table. The field, s_GUID, is a hidden field added to every replicated table in a replicated database.

Sub CheckGUIDType() Dim dbs As Database, rst As Recordset

Set dbs = CurrentDb Set rst = dbs.OpenRecordset("Employees") Debug.Print rst!s_GUID Debug.Print TypeName(rst!s_GUID) Debug.Print TypeName(GuidFromString(rst!s_GUID))End Sub

HasContinued Property

Applies To

Report.

Description

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.

Argument Description

stringexpression A string expression which evaluates to a GUID in string form.

Page 317: Microsoft Access Language

Microsoft Access Language Reference Página 317 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can get the value of the HasContinued property by using a macro or Visual Basic.

Remarks

You can use this 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.

See Also

WillContinue property.

HasData Property

Applies To

Report.

Description

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.

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.

Value Description

–1 The object has data.

Page 318: Microsoft Access Language

Microsoft Access Language Reference Página 318 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can get the value of the HasData property by using a macro or Visual Basic.

Remarks

You can use this 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

See Also

NoData event.

HasModule Property

Applies To

Form, Report.

Description

You can use the HasModule property to specify or determine whether a form or report has a class module. Setting this property to No can improve the performance and decrease the size of your database.

Setting

The HasModule property uses the following settings.

You can set the HasModule property by using the form or report's property sheet, a macro, or Visual Basic.

0 The object doesn't have data.

1 The object is unbound.

Setting Description Visual Basic

Yes The form or report has a class module. True (–1)

No (Default) The form or report doesn't have a class module.

False (0)

Page 319: Microsoft Access Language

Microsoft Access Language Reference Página 319 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The HasModule property can be set only in form or report Design view but can be read in any view.

Remarks

Forms or reports that have the HasModule property set to No are considered lightweight objects. Lightweight objects are smaller and typically load and display faster than objects with associated class modules. In many cases, a form or report doesn't need to use event procedures and doesn't require a class module.

If your application uses a switchboard form to navigate to other forms, instead of using command buttons with event procedures, you can use a command button with a macro or hyperlink. For example, to open the Employees form from a command button on a switchboard, you can set the control's HyperlinkSubAddress property to "Form Employees."

Lightweight objects don't appear in the Object Browser and you can't use the New keyword to create a new instance of the object. A lightweight form or report can be used as a subform or subreport and will appear in the Forms or Reports collection. Lightweight objects support the use of macros, and public procedures that exist in standard modules when called from the object's property sheet.

Microsoft Access sets the HasModule property to True as soon as you attempt to view an object's module, even if no code is actually added to the module. For example, selecting Code from the View menu for a form in Design view causes Microsoft Access to add a class module to the Form object and set its HasModule property to True. You can add a class module to an object in the same way by setting the HasModule property to Yes in an object's property sheet.

Warning If you set the HasModule property to No by using an object's property sheet or set it to False by using Visual Basic, Microsoft Access deletes the object's class module and any code it may contain.

When you use a method of the Module object or refer to the Module property for a form or report in Design view, Microsoft Access creates the associated module and sets the object's HasModule property to True. If you refer to the Module property of a form or report at run-time and the object has its HasModule property set to False, an error will occur.

Objects created by using the CreateForm or CreateReport functions are lightweight by default.

See Also

Module property.

Height, Width Properties

Applies To

l Height property — ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form section, Image control, Label

Page 320: Microsoft Access Language

Microsoft Access Language Reference Página 320 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

control, Line control, List Box control, Option Button control, Option Group control, Page, Rectangle control, Report section, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

l Width property — ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Page, Rectangle control, Report, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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.

Notes

l The Height property applies only to form sections and report sections, not to forms and reports.

l The Width property applies only to forms and reports, not to form sections and report sections.

l Both properties apply to controls on forms and reports.

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 Properties dialog box in Windows Control Panel, specify the unit, such as cm or in (for example, 5 cm or 3 in). The setting for the Width property must be a value from 0 to 22 inches (55.87 cm).

You can set these properties by using the object's property sheet, a macro, or Visual Basic.

For controls, you can set the default for these properties by using the default control style or the DefaultControl method in Visual Basic.

In Visual Basic, use a numeric expression to set the value of each property. Values are expressed in twips.

For report sections, you can't use a macro or Visual Basic to set the Height property when you print or preview a report. For report controls, you can set the Height and Width properties when you print or preview a report only by using a macro or an event procedure specified in a section's OnFormat event property setting.

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 Print 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 Design View or report Design view.

The height of sections and the 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

Page 321: Microsoft Access Language

Microsoft Access Language Reference Página 321 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

controls with different border widths align correctly. The margins for forms and reports are set in the Page Setup dialog box, available by clicking Page Setup on the File menu.

Note To set the left and top location of an object, use the Left and Top properties.

See Also

BorderWidth property, Left, Top properties, MoveSize action.

Example

The following code resizes a command button to a 1-inch by 1-inch square button (the default unit of measurement in Visual Basic is twips; 1440 twips equals one inch):

Me!cmdSizeButton.Height = 1440 ' 1440 twips = 1 inch.Me!cmdSizeButton.Width = 1440

HelpContextID, HelpFile Properties

Applies To

l HelpContextID property — ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Image control, Label control, List Box control, Option Button control, Option Group control, Page, Report, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

l HelpFile property — Form, Report.l Descriptionl The HelpContextID property specifies the context ID of a topic in the custom Help file

specified by the HelpFile property setting.l The HelpFile property specifies the name of a custom Help file for the current form or

report.

Setting

l For the HelpContextID property, enter a Long Integer value between 0 and 2,147,483,647 representing the context ID of the Help file topic you want to display. The default setting is 0.

l For the HelpFile property, enter a string expression that contains the path and file name of a custom Help file created with the Windows Help Compiler.

You can set these properties by using the property sheet, a macro, or Visual Basic. These properties don't apply to controls on reports.

Remarks

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.

You can create a custom Help file to document forms, reports, or applications you create with Microsoft Access.

Page 322: Microsoft Access Language

Microsoft Access Language Reference Página 322 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

ControlTipText property, HelpContext, HelpFile properties ("DAO Language Reference"), MsgBox function.

HideDuplicates Property

Applies To

Check Box control, Combo Box control, List Box control, Option Button control, Option Group control, Text Box control, Toggle Button control.

Description

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.

True (–1)

Page 323: Microsoft Access Language

Microsoft Access Language Reference Página 323 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by 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 by using only the detail section rather than a group header and the detail section.

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 IntegerintCurVal = Me!CategoryName.HideDuplicates

Hourglass Action

Description

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 has the following argument.

Remarks

No (Default) The control is visible regardless of the value in the preceding record.

False (0)

Action argument

Description

Hourglass On Click Yes (display the icon) or No (display the normal mouse pointer) in the Hourglass On box in the Action Arguments section of the Macro window. The default is Yes.

Page 324: Microsoft Access Language

Microsoft Access Language Reference Página 324 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

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

Notes

l 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 of Windows Control Panel (the default is an animated hourglass icon).

l In Windows NT, this is the icon you set for Wait in the Cursors dialog box of Windows Control Panel (the default is also an hourglass icon).

l 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.

See Also

Echo action, Hourglass method.

Hourglass Method

Applies To

DoCmd object.

Description

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 has the following argument.

Argument Description

hourglasson Use True (–1) to display the hourglass icon (or another icon you've chosen). Use False (0) to display the normal mouse pointer.

Page 325: Microsoft Access Language

Microsoft Access Language Reference Página 325 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

DoCmd object, Echo method (Application object), Hourglass action, SetWarnings method.

Example

The following example uses the Hourglass method to display an hourglass icon (or another icon you've chosen) while your Visual Basic code is executing:

DoCmd.Hourglass True

hWnd Property

Applies To

Form, Report.

Description

You can use the hWnd property to determine the handle (a unique Long Integer value) assigned by Microsoft Windows to the current window.

Setting

This property is read-only and is available only by using 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 public variable.

See Also

Declare statement, hWndAccessApp property.

Example

The following example uses the hWnd property with the Windows 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 Long

Sub Form_Activate()

Page 326: Microsoft Access Language

Microsoft Access Language Reference Página 326 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Dim intWindowHandle As Long intWindowHandle = Screen.ActiveForm.hWnd If Not IsZoomed(intWindowHandle) Then DoCmd.Maximize End IfEnd Sub

hWndAccessApp Property

Applies To

Application object.

Description

You can use the hWndAccessApp property to determine the handle assigned by Microsoft Windows 95 to the main Microsoft Access window.

Setting

The hWndAccessApp property is a Long Integer value set by Microsoft Access and is read-only.

Remarks

You can use this property by using Visual Basic when making calls to Windows 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.

See Also

Application object, hWnd property.

Hyperlink Property

Applies To

Combo Box control, Command Button control, Image control, Label control, Text Box control.

Description

You can use the Hyperlink property to return a reference to a hyperlink object. You can use the Hyperlink property to access the properties and methods of a Hyperlink object associated with a control.

Setting

Page 327: Microsoft Access Language

Microsoft Access Language Reference Página 327 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The Hyperlink property is available only by using Visual Basic.

See Also

AddToFavorites method, Follow method, FollowHyperlink method, HyperlinkAddress property, HyperlinkPart function, HyperlinkSubAddress property.

Example

The CreateHyperlink procedure in the following example sets the hyperlink properties for a command button, label, or image control to the address and subaddress values passed to the procedure. The address setting is an optional argument, because a hyperlink to an object in the current database uses only the subaddress setting, To try this example, create a form with two text box controls (txtAddress and txtSubAddress) and a command button (cmdFollowLink) and paste the following into the Declarations section of the form's module:

Private Sub cmdFollowLink_Click() CreateHyperlink Me!cmdFollowLink, Me!txtSubAddress, Me!txtAddressEnd Sub

Sub CreateHyperlink(ctlSelected As Control, strSubAddress As String, _ Optional strAddress As String) Dim hlk As Hyperlink Select Case ctlSelected.ControlType Case acLabel, acImage, acCommandButton Set hlk = ctlSelected.Hyperlink With hlk If Not IsMissing(strAddress) Then .Address = strAddress Else .Address = "" End If .SubAddress = strSubAddress .Follow .Address = "" .SubAddress = "" End With Case Else MsgBox "The control '" & ctlSelected.Name _ & "' does not support hyperlinks." End SelectEnd Sub

HyperlinkAddress Property

Applies To

Command Button control, Image control, Label control.

Description

You can use the HyperlinkAddress property to specify or determine the path to an object, document, Web page or other destination for a command button, image control, or label control.

Setting

The HyperlinkAddress property is a string expression representing the path to a file (UNC path) or

Page 328: Microsoft Access Language

Microsoft Access Language Reference Página 328 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Web page (URL).

You can set the HyperlinkAddress property by using the control's property sheet, a macro, or Visual Basic.

You can also use the Insert Hyperlink dialog box to set this property by clicking the Build button to the right of the property box in the property sheet.

Note When you create a hyperlink by using the Insert Hyperlink dialog box, Microsoft Access automatically sets the HyperlinkAddress property to the location specified in the Link To File Or URL box. The HyperlinkSubAddress property is set to the location specified in the Named Location In File box.

If you copy a hyperlink from another application and paste it into a form or report, Microsoft Access creates a label control with its caption, HyperlinkAddress property, and HyperlinkSubAddress property automatically set.

Remarks

When you move the cursor over a command button, image control, or label control whose HyperlinkAddress property is set, the cursor changes to an upward-pointing hand. Clicking the control displays the object or Web page specified by the link.

To open objects in the current database, leave the HyperlinkAddress property blank and specify the object type and object name you want to open in the HyperlinkSubAddress property by using the syntax "objecttype objectname." If you want to open an object contained in another Microsoft Access database, enter the database path and file name in the HyperlinkAddress property and specify the database object to open by using the HyperlinkSubAddress property.

The HyperlinkAddress property can contain an absolute or a relative path to a target document. An absolute path is a fully qualified URL or UNC path to a document. A relative path is a path related to the base path specified in the Hyperlink Base setting in the DatabaseName Properties dialog box (available by clicking Database Properties on the File menu) or to the current database path. If Microsoft Access can't resolve the HyperlinkAddress property setting to a valid URL or UNC path, it will assume you've specified a path relative to the base path contained in the Hyperlink Base setting or the current database path.

Note When you follow a hyperlink to another Microsoft Access database object, the database Startup properties are applied. For example, if the destination database has a Display form set, that form is displayed when the database opens.

The following table contains examples of HyperlinkAddress and HyperlinkSubAddress property settings.

HyperlinkAddress HyperlinkSubAddress Description

http://www.microsoft.com/ The Microsoft home page on the Web.

Page 329: Microsoft Access Language

Microsoft Access Language Reference Página 329 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

See Also

Hyperlink property, HyperlinkPart function, HyperlinkSubAddress property.

Example

See the Hyperlink property example.

C:\Program Files\Microsoft Office\Office\Samples\Cajun.htm

The Cajun Delights page in the Access sample applications subdirectory.

C:\Program Files\Microsoft Office\Office\Samples\Cajun.htm

NewProducts The "NewProducts" Name tag in the Cajun Delights page.

HyperlinkAddress HyperlinkSubAddress Description

C:\Personal\MyResume.doc References The bookmark named "References" in the Microsoft Word document "MyResume.doc".

C:\Finance\First Quarter.xls Sheet1!TotalSales The range named "TotalSales" in the Microsoft Excel spreadsheet "First Quarter.xls".

C:\Presentation\NewPlans.ppt 10 The 10th slide in the Microsoft PowerPoint document "NewPlans.ppt".

Page 330: Microsoft Access Language

Microsoft Access Language Reference Página 330 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

HyperlinkPart Function

Applies To

Application object.

Description

The HyperlinkPart function returns information about data stored as a Hyperlink data type. The data in a Hyperlink field can contain up to three parts in the following format:

displaytext#address#subaddress

Syntax

object.HyperlinkPart(hyperlink As Variant[, part As Integer])

The HyperlinkPart function has the following arguments.

(continued)

Argument Description

object Optional. The Application object.

hyperlink A Variant representing the data stored in a Hyperlink field.

part Optional. The value for the part argument is an intrinsic constant representing the information you want returned by the HyperlinkPart function:

Constant Value Description

acDisplayedValue 0 (Default) The underlined text displayed in a hyperlink.

acDisplayText 1 The displaytext part of a Hyperlink field.

Page 331: Microsoft Access Language

Microsoft Access Language Reference Página 331 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You use the HyperlinkPart function to return one of three values from a Hyperlink field or the displayed value. The value returned depends on the setting of the part argument. The part argument is optional. If it's not used, the function returns the value Microsoft Access displays for the hyperlink (which corresponds to the acDisplayedValue setting for the part argument). The returned values can be one of the three parts of the Hyperlink field (displaytext, address, or subaddress) or the value Microsoft Access displays for the hyperlink.

Note If you use the HyperlinkPart function in a query, the part argument is required and you can't use the constants listed above but must use the actual value instead.

When a value is provided in the displaytext part of a Hyperlink field, the value displayed by Microsoft Access will be the same as the displaytext setting. When there's no value in the displaytext part of a Hyperlink field, the value displayed will be the address or subaddress part of the Hyperlink field, depending on which value is first present in the field.

The following table shows the values returned by the HyperlinkPart function for data stored in a Hyperlink field.

acAddress 2 The address part of a Hyperlink field.

acSubAddress 3 The subaddress part of a Hyperlink field.

Hyperlink field data HyperlinkPart function returned values

#http://www.microsoft.com# acDisplayedValue: http://www.microsoft.com

acDisplayText:

acAddress: http://www.microsoft.com

acSubAddress:

Microsoft#http://www.microsoft.com# acDisplayedValue: Microsoft

acDisplayText: Microsoft

acAddress: http://www.microsoft.com

acSubAddress:

Page 332: Microsoft Access Language

Microsoft Access Language Reference Página 332 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

When you add an address part to a Hyperlink field by using the Insert Hyperlink dialog box (available by clicking Hyperlink on the Insert menu) or by typing an address part directly into a Hyperlink field, Microsoft Access adds the two # symbols that delimit parts of the hyperlink data.

You can add or edit the displaytext part of a hyperlink field by right-clicking a hyperlink in a table, pointing to Hyperlink on the shortcut menu, and then typing the display text in the Display Text box.

When you add data to a Hyperlink field directly or by using DAO methods, you must include the two # symbols to delimit the parts of the hyperlink data.

See Also

DataType property, FollowHyperlink method, Hyperlink property, HyperlinkAddress property, HyperlinkSubAddress property.

Example

The following example uses all four of the part argument constants to display information returned by the HyperlinkPart function for each record in a table containing a Hyperlink field. To try this example, paste the DisplayHyperlinkParts procedure into the Declarations section of a module. You can call the DisplayHyperlinkParts procedure from the Debug window, passing to it the name of a table containing hyperlinks and the name of the field containing Hyperlink data. For

Hyperlink field data HyperlinkPart function returned values

Customers##Form Customers

acDisplayedValue: Customers

acDisplayText: Customers

acAddress:

acSubAddress: Form Customers

##Form Customers acDisplayedValue: Form Customers

acDisplayText:

acAddress:

acSubAddress: Form Customers

Page 333: Microsoft Access Language

Microsoft Access Language Reference Página 333 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

example:

DisplayHyperlinkParts "MyHyperlinkTableName", "MyHyperlinkFieldName"

Sub DisplayHyperlinkParts(strTable As String, strField As String) Dim dbs As Database, rst As Recordset Dim strMsg As String

Set dbs = CurrentDb Set rst = dbs.OpenRecordset(strTable)

While Not rst.EOF ' For each record in table. strMsg = "DisplayValue = " & HyperlinkPart(rst(strField), _ acDisplayedValue) & vbCrLf & "DisplayText = " _ & HyperlinkPart(rst(strField), acDisplayText) _ & vbCrLf & "Address = " & HyperlinkPart(rst(strField), acAddress) _ & vbCrLf & "SubAddress = " & HyperlinkPart(rst(strField), acSubAddress) ' Show parts returned by HyperlinkPart function. MsgBox strMsg rst.MoveNext WendEnd Sub

When you use the HyperlinkPart function in a query, the part argument is required. For example, the following SQL statement uses the HyperlinkPart function to return information about data stored as a Hyperlink data type in the URL field of the Links table:

SELECT Links.URL, HyperlinkPart([URL],0)AS Display, HyperlinkPart([URL],1)AS Name, HyperlinkPart([URL],2)AS Addr, HyperlinkPart([URL],3) AS SubAddrFROM Links;

HyperlinkSubAddress Property

Applies To

Command Button control, Image control, Label control.

Description

You can use the HyperlinkSubAddress property to specify or determine a location within the target document specified by the HyperlinkAddress property. The HyperlinkSubAddress property can be an object within a Microsoft Access database, a bookmark within a Microsoft Word document, a named range within a Microsoft Excel spreadsheet, a slide within a Microsoft PowerPoint presentation, or a location within an HTML document.

Setting

The HyperlinkSubAddress property is a string expression representing a named location within the target document specified by the HyperlinkAddress property.

You can set the HyperlinkSubAddress property by using a control's property sheet, a macro, or Visual Basic.

You can also use the Insert Hyperlink dialog box to set this property by clicking the Build button to the right of the property box in the property sheet.

Page 334: Microsoft Access Language

Microsoft Access Language Reference Página 334 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note When you create a hyperlink by using the Insert Hyperlink dialog box, Microsoft Access automatically sets the HyperlinkAddress property to the location specified in the Link To File Or URL box. The HyperlinkSubAddress property is set to the location specified in the Named Location In File box.

Remarks

When you move the cursor over a command button, image control, or label control whose HyperlinkSubAddress property is set, the cursor changes to an upward-pointing hand. Clicking the control displays the object or Web page specified by the link.

To open objects in the current database, leave the HyperlinkAddress property blank and specify the object type and object name you want to open in the HyperlinkSubAddress property in the format "objecttype objectname." For example, to create a hyperlink for a command button that opens the Employees form you could set the control's HyperlinkSubAddress property to "Form Employees." If you want to open an object contained in another Microsoft Access database, enter the database path and file name in the HyperlinkAddress property and specify the database object to open by using the HyperlinkSubAddress property.

Note When you follow a hyperlink to another Microsoft Access database object, the database Startup properties are applied. For example, if the destination database has a Display form set, that form is displayed when the database opens.

The following table contains shows examples of HyperlinkAddress and HyperlinkSubAddress property settings.

HyperlinkAddress HyperlinkSubAddress Description

http://www.microsoft.com/ The Microsoft home page on the Web.

C:\Program Files\Microsoft Office\Office\Samples\Cajun.htm

The Cajun Delights page in the Access sample applications subdirectory.

C:\Program Files\Microsoft Office\Office\Samples\Cajun.htm

NewProducts The "NewProducts" Name tag in the Cajun Delights page.

Page 335: Microsoft Access Language

Microsoft Access Language Reference Página 335 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

Hyperlink property, HyperlinkAddress property, HyperlinkPart function.

IgnoreNulls Property

Applies To

Index.

Description

You can use the IgnoreNulls property to specify that records with Null values in the indexed fields not be included in the index.

Setting

The IgnoreNulls property uses the following settings.

C:\Personal\MyResume.doc References The bookmark named "References" in the Microsoft Word document "MyResume.doc".

C:\Finance\First Quarter.xls Sheet1!TotalSales The range named "TotalSales" in the Microsoft Excel spreadsheet "First Quarter.xls".

C:\Presentation\NewPlans.ppt 10 The 10th slide in the Microsoft PowerPoint document "NewPlans.ppt".

Page 336: Microsoft Access Language

Microsoft Access Language Reference Página 336 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the Indexes window of table Design view or Visual Basic.

To access the IgnoreNulls property of an index by using Visual Basic, use the DAO IgnoreNulls property.

Remarks

You can define an index for a field to facilitate faster searches for records indexed on 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.

See Also

IgnoreNulls property ("DAO Language Reference"), Index object ("DAO Language Reference"), Indexed property, Indexes collection ("DAO Language Reference"), Primary property, Primary property ("DAO Language Reference"), Unique property, Unique property ("DAO Language Reference").

Example

The following example adds a new index to a TableDef object and sets the IgnoreNulls and Unique properties to True (–1):

Sub NewIndex() Dim dbs As Database, tdf As TableDef Dim idx As Index, fldID As Field, fldName As Field

' Return reference to current database. Set dbs = CurrentDb ' Return reference to Products table. Set tdf = dbs.TableDefs!Products ' Return Index object that points to new index. Set idx = tdf.CreateIndex("IDName") ' Create and append index fields. Set fldID = idx.CreateField("ProductID") Set fldName = idx.CreateField("ProductName") idx.Fields.Append fldID idx.Fields.Append fldName ' Set index properties. idx.IgnoreNulls = True idx.Unique = True ' Append new Index object to Indexes collection. tdf.Indexes.Append idx

Setting Description Visual Basic

Yes Records that contain Null values in the indexed fields aren't included in the index.

True (–1)

No (Default) Records that contain Null values in the indexed fields are included in the index.

False (0)

Page 337: Microsoft Access Language

Microsoft Access Language Reference Página 337 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Set dbs = NothingEnd Sub

ImageHeight Property

Applies To

Image control.

Description

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.

See Also

Height, Width properties, ImageWidth property, SizeToFit method.

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 file name for new bitmap") ctlImage.Height = ctlImage.ImageHeight ctlImage.Width = ctlImage.ImageWidthEnd Sub

ImageWidth Property

Applies To

Image control.

Page 338: Microsoft Access Language

Microsoft Access Language Reference Página 338 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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.

See Also

Height, Width properties, ImageHeight property, SizeToFit method.

Example

See the ImageHeight property example.

Indexed Property

Applies To

Table field.

Description

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 to speed up the search for a specific name.

Setting

The Indexed property uses the following settings.

Setting Description

No (Default) No index.

Page 339: Microsoft Access Language

Microsoft Access Language Reference Página 339 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property only in the Field Properties section in table Design view. You can set a single-field index by setting the Indexed property in the Field Properties section in table Design view. You can set multiple-field indexes in the Indexes window by clicking Indexes on the View menu.

If you add a single-field index in the Indexes window, Microsoft Access will set the Indexed property for the field to Yes.

In Visual Basic, use the DAO CreateIndex method to create an index for a field.

Remarks

Use the Indexed property to find and sort records by 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, Hyperlink, or OLE Object data type fields.

You can create as many indexes as you need. The indexes are created when you save the table 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.

See Also

CreateIndex method ("DAO Language Reference"), IgnoreNulls property, IgnoreNulls property ("DAO Language Reference"), Primary property, Primary property ("DAO Language Reference"), Unique property.

Initialize Event

Yes (Duplicates OK)

The index allows duplicates.

Yes (No Duplicates)

The index doesn't allow duplicates.

Page 340: Microsoft Access Language

Microsoft Access Language Reference Página 340 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Module object.

Description

The Initialize event for a class module occurs when you create an instance of that class module.

Note To run code when the Initialize event occurs, you must place that code within the Initialize event procedure in a class module.

Remarks

The Initialize event occurs when you:

l Create a new instance of a class directly by using the New keyword.l Create an instance of a class indirectly by setting or returning a property or applying a

method defined in the class module.

See Also

Event properties, Terminate event.

Initialize Event — Event Procedures

Description

To create the event procedure for the Initialize event, open the class module and click Class in the Object box. Then click Initialize in the Procedure box.

Syntax

Private Sub Class_Initialize( )

Remarks

You can use this event procedure to run code when an instance of the class is created, or to initialize any data used by the instance of the class.

The Initialize event occurs when you create a new instance of a class by using the New keyword. For example, suppose you have a class named CustomObject. You can add a declaration statement to a procedure in a standard module that creates a new instance of the class CustomObject, as shown in the following example:

Dim obj As New CustomObject

When you run the procedure that contains this declaration, Visual Basic creates a new instance of the CustomObject class, and the Initialize event occurs.

Page 341: Microsoft Access Language

Microsoft Access Language Reference Página 341 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The Initialize event also occurs when you create an instance of a class by setting or returning a property or applying a method defined in the class module. For example, suppose you've defined a Function procedure named ListNames within the CustomObject class module. To run this function from another module, you must qualify it with the name of the class module, as shown in the following example:

CustomObject.ListNames

Qualifying the function with the name of the class module creates an instance of the class module, and the Initialize event occurs.

Example

The following example includes event procedures for the ItemAdded and ItemRemoved events. To try this example, first create a new class module by clicking Class Module on the Insert menu. Paste the following code into the class module and save the module as RefEvents:

' Declare object variable to represent References collection.Public WithEvents evtReferences As References

' When instance of class is created, initialize evtReferences variable.Private Sub Class_Initialize() Set evtReferences = Application.ReferencesEnd Sub

' When instance is removed, set evtReferences to Nothing.Private Sub Class_Terminate() Set evtReferences = NothingEnd Sub

' Display message when reference is added.Private Sub evtReferences_ItemAdded(ByVal Reference As Access.Reference) MsgBox "Reference to " & Reference.Name & " added."End Sub

' Display message when reference is removed.Private Sub evtReferences_ItemRemoved(ByVal Reference As Access.Reference) MsgBox "Reference to " & Reference.Name & " removed."End Sub

The following Function procedure adds a specified reference. When a reference is added, the ItemAdded event procedure defined in the RefEvents class runs.

For example, to set a reference to the calendar control, you could pass the string "C:\Windows\System\Mscal.ocx", if this is the correct location for the calendar control on your computer.

' Create new instance of RefEvents class.Dim objRefEvents As New RefEvents

' Pass file name and path of type library to this procedure.Function AddReference(strFileName As String) As Boolean Dim ref As Reference

On Error GoTo Error_AddReference ' Create new reference on References object variable. Set ref = objRefEvents.evtReferences.AddFromFile(strFileName) AddReference = True

Exit_AddReference: Exit Function

Error_AddReference: MsgBox Err & ": " & Err.Description

Page 342: Microsoft Access Language

Microsoft Access Language Reference Página 342 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

AddReference = False Resume Exit_AddReferenceEnd Function

The next Function procedure removes a specified reference. When a reference is removed, the ItemRemoved event procedure defined in the RefEvents class runs.

For example, to remove a reference to the calendar control, you could pass the string "MSACAL," which is the name of the Reference object that represents the calendar control.

Function RemoveReference(strRefName As String) As Boolean Dim ref As Reference

On Error GoTo Error_RemoveReference ' Return object representing existing reference. Set ref = objRefEvents.evtReferences(strRefName) ' Remove reference from collection. objRefEvents.evtReferences.Remove ref RemoveReference = True

Exit_RemoveReference: Exit Function

Error_RemoveReference: MsgBox Err & ": " & Err.Description RemoveReference = False Resume Exit_RemoveReferenceEnd Function

InputMask Property

Applies To

Combo Box control, Field object, Query field, Table field, Text Box control.

Description

You can use the InputMask property to make data entry easier and to 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) 999-9999. For a list of characters you can use to define the input mask, see the following table.

Page 343: Microsoft Access Language

Microsoft Access Language Reference Página 343 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 a phone number:

Forms!Customers!Telephone.InputMask = "(###) ###-####"

When you create an input mask, you can use special characters to require that certain data be entered (for example, the area code for a phone number) and that other data be optional (such as a telephone extension). 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 by using the following characters.

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 (" ").

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).

Page 344: Microsoft Access Language

Microsoft Access Language Reference Página 344 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 (*).

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 Properties dialog box in 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. 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).

Page 345: Microsoft Access Language

Microsoft Access Language Reference Página 345 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 (in the Field Properties section) or in Design view of the Query window (in the Field Properties property sheet).

You can also set the InputMask property by using 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 not 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 by setting the control's Text property in Visual Basic or by using the SetValue action in a macro.

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 and displayed. The data in the underlying table itself isn't changed; the Format property affects only how the data is displayed.

See Also

AutoTab property, Format property.

Example

The following table shows some useful input masks and the type of values you can enter in them.

Input mask Sample values

(000) 000-0000 (206) 555-0248

(999) 999-9999 (206) 555-0248

( ) 555-0248

(000) AAA-AAAA (206) 555-TELE

Page 346: Microsoft Access Language

Microsoft Access Language Reference Página 346 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

InSelection Property

Applies To

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

Description

You can use the InSelection property to determine or specify whether a control on a form in Design view is selected.

#999 –20

2000

>L????L?000L0 GREENGR339M3

MAY R 452B7

>L0L 0L0 T2F 8M4

00000-9999 98115-

98115-3007

>L<?????????????? Maria

Brendan

SSN 000-00-0000 SSN 555-55-5555

>LL00000-0000 DB51392-0493

Page 347: Microsoft Access Language

Microsoft Access Language Reference Página 347 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The InSelection property uses the following settings.

This property is available only by using 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.

See Also

Control object.

Example

The following function uses the InSelection property to determine whether the strControlName control on a form is selected.

To test this code, paste the IsControlSelected function code in the Declarations section of a code module in the Northwind sample database, open the Customers form in Design view, and select the CompanyName control. Then enter the following line in the Debug window:

? IsControlSelected (Forms!Customers, "CompanyName")

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 Exit Function End If Else IsControlSelected = False End If Next intI End IfEnd Function

Setting Description

True (–1) The control is selected.

False (0) The control isn't selected.

Page 348: Microsoft Access Language

Microsoft Access Language Reference Página 348 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

InsertLines Method

Applies To

Module object.

Description

The InsertLines method inserts a line or group of lines of code in a standard module or a class module.

Syntax

object.InsertLines line, string

The InsertLines method has the following arguments.

Remarks

When you use the InsertLines method, any existing code at the line specified by the line argument moves down.

To add multiple lines, include the intrinsic constant vbCrLf at the desired line breaks within the string that makes up the string argument. This constant forces a carriage return and line feed.

Lines in a module are numbered beginning with one. To determine the number of lines in a module, use the CountOfLines property.

See Also

CountOfLines property, CreateEventProc method, DeleteLines method.

Example

Argument Description

object A Module object.

line The number of the line at which to begin inserting.

string The text to be inserted into the module.

Page 349: Microsoft Access Language

Microsoft Access Language Reference Página 349 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See the CreateEventProc method example.

InsertText Method

Applies To

Form object, Module object, Report object.

Description

The InsertText method inserts a specified string of text into a standard module or a class module.

Syntax

object.InsertText text

The InsertText method has the following arguments.

Remarks

When you insert a string by using the InsertText method, Microsoft Access places the new text at the end of the module, after all other procedures.

To add multiple lines, include the intrinsic constant vbCrLf at the desired line breaks within the string that makes up the text argument. This constant forces a carriage return and line feed.

To specify at which line the text is inserted, use the InsertLines method. To insert code into the Declarations section of the module, use the InsertLines method rather than the InsertText method.

Note In previous versions of Microsoft Access, the InsertText method was a method of the Application object. You can still use the InsertText method of the Application object, but it's recommended that you use the InsertText method of the Module object instead.

See Also

InsertLines method, Module property.

Argument Description

object A Module object.

text The text to be inserted into the module.

Page 350: Microsoft Access Language

Microsoft Access Language Reference Página 350 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

The following example inserts a string of text into a standard module:

Function InsertProc(strModuleName) As Boolean Dim mdl As Module, strText As String

On Error GoTo Error_InsertProc ' Open module. DoCmd.OpenModule strModuleName ' Return reference to Module object. Set mdl = Modules(strModuleName) ' Initialize string variable. strText = "Sub DisplayMessage()" & vbCrLf _ & vbTab & "MsgBox ""Wild!""" & vbCrLf _ & "End Sub" ' Insert text into module. mdl.InsertText strText InsertProc = True

Exit_InsertProc: Exit Function

Error_InsertProc: MsgBox Err & ": " & Err.Description InsertProc = False Resume Exit_InsertProcEnd Function

InsideHeight, InsideWidth Properties

Applies To

Form.

Description

You can use the InsideHeight and InsideWidth properties to determine the height and width (in twips) of the window containing a form.

Setting

l The InsideHeight property. An Integer value expressed in twips that represents the height of a form window.

l The InsideWidth property. An Integer value expressed in twips that represents the width of a form window.

The InsideHeight and InsideWidth properties are available only by using a macro or Visual Basic and can be set at any time.

Remarks

If you want to determine the interior dimensions of the form itself, you use the Width property to determine the form width and the sum of the heights of the form's visible sections to determine its height (the Height property applies only to form sections, not to forms). The interior of a form is the region inside the form, excluding the scroll bars and the record selectors.

Page 351: Microsoft Access Language

Microsoft Access Language Reference Página 351 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can also use the WindowHeight and WindowWidth properties to determine the height and width of the window containing a form.

If a window is maximized, setting these properties doesn't have any effect until the window is restored to its normal size.

See Also

Height, Width properties, WindowHeight, WindowWidth 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 don't 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(acHeader).Height intHeightDetail = frm.Section(acDetail).Height intHeightFooter = frm.Section(acFooter).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 frm.InsideWidth = intTotalFormWidth End If If intWindowHeight <> intTotalFormHeight Then frm.InsideHeight = intTotalFormHeight End IfEnd Sub

IsBroken Property

Applies To

Reference object.

Description

The IsBroken property returns a Boolean value indicating whether a Reference object points to a valid reference in the Windows Registry.

Page 352: Microsoft Access Language

Microsoft Access Language Reference Página 352 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The IsBroken property is available only by using Visual Basic and is read-only.

The default value of the IsBroken property is False (0). The IsBroken property returns True (–1) only if the Reference object no longer points to a valid reference in the Registry.

Remarks

By evaluating the IsBroken property, you can determine whether or not the file associated with a particular Reference object has been moved to a different directory or deleted.

If the IsBroken property is True, Microsoft Access generates an error when you try to read the Name or FullPath properties.

Example

See the FullPath property example.

IsCompiled Property

Applies To

Application object.

Description

The IsCompiled property returns a Boolean value indicating whether the Visual Basic project is in a compiled state.

Setting

The IsCompiled property is available only by using Visual Basic and is read-only.

The IsCompiled property returns True (–1) if the project is in a compiled state.

Remarks

You can force Visual Basic to compile the project from the user interface while in module Design view by clicking Compile All Modules or Compile And Save All Modules on the Debug menu.

The IsCompiled property of the Application object is False (0) when the project has never been fully compiled, if a module has been added, edited, or deleted after compilation, or if a module hasn't been saved in a compiled state.

IsVisible Property

Page 353: Microsoft Access Language

Microsoft Access Language Reference Página 353 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

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

Description

You can use the IsVisible property in Visual Basic to determine whether a control on a report is visible.

Setting

The IsVisible property uses the following settings.

You can set the IsVisible property only in the Print event of a report section that contains the control.

Remarks

You can use the IsVisible property together with the HideDuplicates property to determine when a control on a report is visible and show or hide other controls as a result. For example, you could hide a line control when a text box control is hidden because it contains duplicate values.

See Also

HideDuplicates property.

Example

The following example uses the IsVisible property of a text box to control the display of a line control on a report. The report is based on a Products table and uses three controls with the following properties.

Setting Description

True (–1) (Default) The control is visible.

False (0) The control isn't visible.

Page 354: Microsoft Access Language

Microsoft Access Language Reference Página 354 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Paste the following code into the Declarations section of the report module, and then view the report to see the line formatting controlled by the IsVisible property:

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer) If Me!CategoryID.IsVisible Then Me!Line0.Visible = True Else Me!Line0.Visible = False End IfEnd Sub

Item Method

Applies To

References collection.

Description

The Item method returns a specific member of a collection either by position or by key.

Syntax

object.Item(index)

The Item method has the following arguments.

Properties Line control Text box #1 Text box #2

Name Line0 CategoryID ProductName

ControlSource CategoryID ProductName

HideDuplicates Yes No

Left 0 0 2.0

Top 0 .1 .1

Width 4.0 1.0 1.0

Page 355: Microsoft Access Language

Microsoft Access Language Reference Página 355 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If the value provided for the index argument doesn't match any existing member of the collection, an error occurs.

The Item method is the default member of the References collection, so you don't have to specify it explicitly. For example, the following two lines of code are equivalent:

Debug.Print References(1).Name

Debug.Print References.Item(1).Name

See Also

Count property, References collection.

Item Property (Collections)

Applies To

Controls collection, Forms collection, Modules collection, Pages collection, Properties collection, Reports collection.

Description

The Item property returns a specific member of a collection either by position or by index.

Setting

object.Item(index)

The Item property uses the following settings.

Argument Description

object The References collection.

index An expression that specifies the position of a member of the collection referred to by the object argument. If a numeric expression, the index argument must be a number from 1 to the value of the collection's Count property. If a string expression, the index argument must be the name of a member of the collection.

Page 356: Microsoft Access Language

Microsoft Access Language Reference Página 356 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The Item property is available only by using Visual Basic and is read-only.

Remarks

If the value provided for the index argument doesn't match any existing member of the collection, an error occurs.

The Item property is the default member of a collection, so you don't have to specify it explicitly. For example, the following two lines of code are equivalent:

Debug.Print Modules(0)Debug.Print Modules.Item(0)

See Also

Controls collection, Count property, Count property ("DAO Language Reference"), Forms collection, Modules collection, Pages collection, Properties collection ("DAO Language Reference"), Reports collection.

Item Property (ObjectFrame Control)

Applies To

Chart control, Unbound Object Frame control.

Description

You can use the Item property to get a description of the linked data displayed in a chart control or unbound object frame.

Setting Description

object One of the following collections: Controls, Forms, Modules, Pages, Properties, Reports.

index An expression that specifies the position of a member of the collection referred to by the object argument. If a numeric expression, the index argument must be a number from 0 to the value of the collection's Count property minus 1. If a string expression, the index argument must be the name of a member of the collection.

Page 357: Microsoft Access Language

Microsoft Access Language Reference Página 357 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The Item property setting is a string expression and is read-only in all views.

Note If you are using Automation (formerly called OLE Automation), and need to specify a range of data, use the SourceItem property.

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 unbound object frame by clicking Paste Special on the Edit menu, Microsoft Access sets the SourceObject, OLEClass, and Item properties. The following table shows typical property settings for various OLE objects.

See Also

OLEClass property, OLEType property, SourceItem property, SourceObject property.

ItemAdded Event

Applies To

References collection.

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

Page 358: Microsoft Access Language

Microsoft Access Language Reference Página 358 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

The ItemAdded event occurs when a reference is added to the project from Visual Basic.

Notes

l The ItemAdded event applies to the References collection. It isn't associated with a control, form, or report, as are most other events. Therefore, in order to create a procedure definition for the ItemAdded event procedure, you must use a special syntax.

l The ItemAdded event can run only an event procedure when it occurs, it cannot run a macro.

Remarks

This event occurs only when you add a reference from code. It doesn't occur when you add a reference from the References dialog box, available by clicking References on the Tools menu when the Module window is the active window.

See Also

ItemRemoved event.

ItemAdded Event — Event Procedures

Description

To create an event procedure that runs when the ItemAdded event occurs, follow the steps included in the Remarks section of this topic.

Syntax

Private Sub evtReferences_ItemAdded(reference)

The ItemAdded event procedure has the following arguments.

Argument Description

evtReferences An object variable representing the References collection. You must declare this object variable in a class module by using the WithEvents keyword.

reference The Reference object that has been added to the References collection.

Page 359: Microsoft Access Language

Microsoft Access Language Reference Página 359 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The ItemAdded event procedure can contain code that you want to run when a reference to a type library is added to the project. You can add a reference from Visual Basic by using the AddFromFile or AddFromGUID method to add a Reference object to the References collection.

To create the ItemAdded event procedure:

1. 1. Using the WithEvents keyword, declare an object variable of type References in the Declarations section of a class module. Microsoft Access uses this object variable to define the event procedure for the ItemAdded event. The following line of code shows a typical WithEvents declaration:

Public WithEvents evtReferences As References

2. 2. Create an event procedure definition within the class module by selecting the name of the References object variable from the Object box in the Module window. For example, if you use the declaration shown in the preceding step, you'll see evtReferences in the Object drop-down box. Then select the ItemAdded event in the Procedure box.

3. 3. Add the code that will run when the event occurs. For example, if you want to display a message box stating that a reference has been added to the project, add that code to the event procedure.

4. 4. Assign the References collection to the References object variable that you declared with the WithEvents keyword. This assignment statement should be within a procedure that runs before the ItemAdded event will occur. For example, you could include this statement within the Initialize event of the class module in which you declared the object variable. Then when you create an instance of the class, the object variable is automatically initialized. If you're using the evtReferences object variable, this event procedure would appear as follows:

Private Sub Class_Initialize() Set evtReferences = Application.ReferencesEnd Sub

Note If you've already followed the preceding steps to create an event procedure for the ItemRemoved event, you don't need to repeat them for the ItemAdded event. You can use the same References object variable for both.

In order to trigger the ItemAdded event, you must create the new reference by using the References object variable that you declared with the WithEvents keyword.

To add a reference and trigger the event:

1. 1. Within a standard module, create a new instance of the class within which you declared the References object variable. For example, if the name of the class is RefEvents, you can create a new instance of the class and assign it to an object variable with the following declaration statement. This statement can exist at the module level or within a procedure.

Dim objRefEvents As New RefEvents

2. 2. Within a Sub or Function procedure, create a new Reference object by using the AddFromFile or AddFromGUID method of the object variable that represents the References collection (evtReferences). Since the ItemAdded event in the class module is defined in association with a particular References object variable, you must create the new

Page 360: Microsoft Access Language

Microsoft Access Language Reference Página 360 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Reference object by using this variable. Otherwise, the event won't occur.

Note that you must qualify the References object variable with the name of the class in which it's declared.

Once you've completed all the preceding steps, you can add a new reference with a procedure such as the following:

Function AddReference(strFileName As String) Dim ref As Reference ' Create new instance of RefEvents class. Dim objRefEvents As New RefEvents

' Creates reference on References collection ' variable defined in RefEvents class. Set ref = objRefEvents.evtReferences.AddFromFile(strFileName)End Function

Notes

l The procedure that initializes the References object variable must be within the same scope as the object variable declaration. For example, if you declared the References object variable as Private within a class module, then you must initialize the variable in a procedure within that same class module.

l You can include the ItemAdded event procedure only in a class module.l Once you declare a module-level variable to represent the References collection, you can

use that variable to create event procedure definitions for both the ItemAdded event and the ItemRemoved event.

l If you have multiple ItemAdded event procedures within a single project, each one will run when the event occurs, but they won't run in any specified order. Therefore, it's advisable to create only one ItemAdded event procedure in a project and to include all code to be run when the event occurs in that event procedure.

l The ItemAdded event occurs after the reference has been added to the project.

See Also

ItemAdded event, ItemRemoved event.

Example

See the Initialize event — event procedures example.

ItemData Property

Applies To

Combo Box control, Control object, List Box control.

Description

The ItemData property returns the data in the bound column for the specified row in a combo box or list box.

Page 361: Microsoft Access Language

Microsoft Access Language Reference Página 361 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Syntax

control.ItemData(rowindex)

The ItemData property has the following arguments.

Remarks

The ItemData property 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 property to return the data for the bound column in each row.

You can also use the ItemData property 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 property 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 isn't the bound column.

See Also

BoundColumn property.

Example

The following example prints the value of the bound column for each selected row in a list box EmployeeList on an Employees form. The list box's MultiSelect property must be set to Simple or Extended.

Sub RowsSelected() Dim ctlList As Control, varItem As Variant

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 the rowindex argument.

Page 362: Microsoft Access Language

Microsoft Access Language Reference Página 362 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' Return Control object variable pointing to list box. Set ctlList = Forms!Employees!EmployeeList ' Enumerate through selected items. For Each varItem in ctlList.ItemsSelected ' Print value of bound column. Debug.Print ctlList.ItemData(varItem) Next varItemEnd Sub

ItemRemoved Event

Applies To

References collection.

Description

The ItemRemoved event occurs when a reference is removed from the project.

Notes

l The ItemRemoved event applies to the References collection. It isn't associated with a control, form, or report, as are most other events. Therefore, in order to create a procedure definition for the ItemRemoved event procedure, you must use a special syntax.

l The ItemRemoved event can run only an event procedure when it occurs, it cannot run a macro.

Remarks

This event occurs only when you remove a reference from code. It doesn't occur when you remove a reference from the References dialog box, available by clicking References on the Tools menu when the Module window is the active window.

See Also

ItemAdded event.

ItemRemoved Event — Event Procedures

Description

To create an event procedure that runs when the ItemRemoved event occurs, follow the steps included in the Remarks section of this topic.

Syntax

Private Sub evtReferences_ItemRemoved(reference)

Page 363: Microsoft Access Language

Microsoft Access Language Reference Página 363 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The ItemRemoved event procedure has the following arguments.

Remarks

The ItemRemoved event procedure can contain code that you want to run when a reference to a type library is removed from the project. You can remove a reference from Visual Basic by using the Remove method to remove a Reference object from the References collection.

To create the ItemRemoved event procedure:

1. Using the WithEvents keyword, declare an object variable of type References in the Declarations section of a class module. Microsoft Access uses this object variable to define the event procedure for the ItemRemoved event. The following line of code shows a typical WithEvents declaration:

Public WithEvents evtReferences As References

2. 2. Create an event procedure definition within the class module by selecting the name of the References object variable from the Object box in the Module window. For example, if you use the declaration shown in the preceding step, you'll see evtReferences in the Object drop-down box. Then select the ItemRemoved event in the Procedure box.

3. 3. Add the code that will run when the event occurs. For example, if you want to display a message box stating that a reference has been removed from the project, add that code to the event procedure.

4. 4. Assign the References collection to the References object variable that you declared with the WithEvents keyword. This assignment statement should be within a procedure that runs before the ItemRemoved event will occur. For example, you could include this statement within the Initialize event of the class module in which you declared the object variable. Then when you create an instance of the class, the object variable is automatically initialized. If you're using the evtReferences object variable, this event procedure would appear as follows:

Private Sub Class_Initialize() Set evtReferences = Application.ReferencesEnd Sub

Note If you've already followed the preceding steps to create an event procedure for the ItemAdded event, you don't need to repeat them for the ItemRemoved event. You can use the same References object variable for both.

Argument Description

evtReferences An object variable representing the References collection. You must declare this object variable in a class module by using the WithEvents keyword.

reference The Reference object that has been removed from the References collection.

Page 364: Microsoft Access Language

Microsoft Access Language Reference Página 364 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

In order to trigger the ItemRemoved event, you must remove the existing reference by using the References object variable that you declared with the WithEvents keyword.

To remove a reference and trigger the event:

1. 1. Within a standard module, create a new instance of the class within which you declared the References object variable. For example, if the name of the class is RefEvents, you can create a new instance of the class and assign it to an object variable with the following declaration statement. This statement can exist at the module level or within a procedure.

Dim objRefEvents As New RefEvents

2. Within a Sub or Function procedure, create a new Reference object by using the Remove method of the object variable that represents the References collection (evtReferences). Since the ItemRemoved event in the class module is defined in association with a particular References object variable, you must create the new Reference object by using this variable. Otherwise, the event won't occur.

Note that you must qualify the References object variable with the name of the class in which it's declared.

Once you've completed all the preceding steps, you can remove an existing reference with a procedure such as the following:

Function RemoveReference(strRefName As String) Dim ref As Reference ' Create new instance of RefEvents class. Dim objRefEvents As New RefEvents

' Creates reference on References collection ' variable defined in RefEvents class. Set ref = objRefEvents.evtReferences(strRefName) objRefEvents.evtReferences.Remove refEnd Function

Notes

l The procedure that initializes the References object variable must be within the same scope as the object variable declaration. For example, if you declared the References object variable as Private within a class module, then you must initialize the variable in a procedure within that same class module.

l You can include the ItemRemoved event procedure only in a class module.l Once you declare a module-level variable to represent the References collection, you can

use that variable to create event procedure definitions for both the ItemRemoved event and the ItemAdded event.

l If you have multiple ItemRemoved event procedures within a single project, each one will run when the event occurs, but they won't run in any specified order. Therefore, it's advisable to create only one ItemRemoved event procedure in a project and to include all code to run when the event occurs in that event procedure.

l The ItemRemoved event occurs after the reference has been removed from the project.

See Also

ItemAdded event, ItemRemoved event.

Page 365: Microsoft Access Language

Microsoft Access Language Reference Página 365 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

See the Initialize event — event procedures example.

ItemsSelected Collection

Description

The ItemsSelected collection provides a way to access data in the selected rows of a list box control.

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 property to retrieve data from selected rows in a list box or combo box. You can list the ItemsSelected collection by using the For Each...Next statement.

For example, if you have an Employees list box on a form, you can list the ItemsSelected collection and use the control's ItemData property 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, set the control's MultiSelect property to Simple or Extended.

The ItemsSelected collection has no methods and one property, the Count property.

Properties

Count property.

See Also

For Each...Next statement, ItemData property, MultiSelect property.

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

Page 366: Microsoft Access Language

Microsoft Access Language Reference Página 366 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

For Each varItm In ctl.ItemsSelected Debug.Print ctl.ItemData(varItm) Next varItmEnd 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 varItmEnd Sub

KeepTogether Property — Groups

Applies To

Report.

Description

You can use the KeepTogether property for a group in a report to keep parts of a group — including the group header, detail section, and group footer — together on the same page. For example, you might want a group header to always be printed on the same page with the first detail section.

Setting

The KeepTogether property for a group 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

Page 367: Microsoft Access Language

Microsoft Access Language Reference Página 367 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

KeepTogether Property — Sections

Applies To

Form, Form section, Report, Report section.

Description

You can use the KeepTogether property for a section to print a form or 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 form and report sections (except page headers and page footers).

Setting

The KeepTogether property for a section uses the following settings.

You can set this property by using the section's property sheet, a macro, or Visual Basic.

You can set the KeepTogether property for a section only in form Design view or report Design view.

Remarks

With First Detail

Prints the group header on a page only if it can also print the first detail record.

2

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)

Page 368: Microsoft Access Language

Microsoft Access Language Reference Página 368 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Usually, when a page break occurs while a section is being printed, Microsoft Access continues printing the section on the next page. By 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.

If the KeepTogether property for a group is set to Whole Group or With First Detail and the KeepTogether property for a section is set to No, the KeepTogether property setting for the section is ignored.

See Also

ForceNewPage property, Format event, KeepTogether property — groups.

Example

The following example returns the KeepTogether property setting for a report's detail section and assigns the value to the intGetVal variable.

Dim intGetVal As IntegerintGetVal = Me.Section(acDetail).KeepTogether

KeyDown, KeyUp Events

Applies To

Bound Object Frame control, Check Box control, Combo Box control, Command Button control, Form, List Box control, Option Button control, Tab control, Text Box control, Toggle Button control.

Description

l The KeyDown event occurs 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 by using the SendKeys action in a macro or the SendKeys statement in Visual Basic.

l The KeyUp event occurs 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 by 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, not controls on a report.

Remarks

To run a macro or event procedure when these events occur, set the OnKeyDown or OnKeyUp property to the name of the macro or to [Event Procedure].

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.

Page 369: Microsoft Access Language

Microsoft Access Language Reference Página 369 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 and KeyPress events alternate repeatedly (KeyDown, KeyPress, KeyDown, KeyPress, and so on) 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:

l Extended character keys, such as function keys.l Navigation keys, such as HOME, END, PAGE UP, PAGE DOWN, UP ARROW, DOWN ARROW,

RIGHT ARROW, LEFT ARROW, and TAB.l Combinations of keys and standard keyboard modifiers (SHIFT, CTRL, or ALT keys).l The numeric keypad and keyboard number keys.

The KeyDown and KeyUp events don't occur when you press:

l The ENTER key if the form has a command button for which the Default property is set to Yes.

l The ESC key if the form has a command button for which the Cancel property is set to Yes.

Tip 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.

If a modal dialog box is displayed as a result of pressing or sending a key, the KeyDown and KeyPress events occur, but the KeyUp event doesn't occur.

See Also

Change event, Enter, Exit events, Event properties, GotFocus, LostFocus events, KeyPress event, KeyPreview property, NotInList event, SendKeys action, SendKeys statement.

KeyDown, KeyUp Events — Event Procedures

Description

To create an event procedure that runs when the KeyDown or KeyUp event occurs, set the OnKeyDown or OnKeyUp property to [Event Procedure], and click the Build button.

Syntax

Page 370: Microsoft Access Language

Microsoft Access Language Reference Página 370 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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)

The KeyDown and KeyUp events have the following arguments.

Argument Description

controlname The name of the control whose KeyUp or KeyDown event procedure you want to run.

KeyCode A key code, such as vbKeyF1 (the F1 key) or vbKeyHome (the HOME key). To specify key codes, use the intrinsic constants shown in the Object Browser. You can prevent an object from receiving a keystroke by setting KeyCode to 0.

Page 371: Microsoft Access Language

Microsoft Access Language Reference Página 371 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

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...End If

You can use the KeyDown and KeyUp event procedures to interpret the uppercase and lowercase

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 The bit mask for the SHIFT key.

acCtrlMask The bit mask for the CTRL key.

acAltMask The bit mask for the ALT key.

Page 372: Microsoft Access Language

Microsoft Access Language Reference Página 372 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

KeyDown, KeyUp events — macros.

Example

The following example determines whether you have pressed the SHIFT, CTRL, or ALT key.

To try the example, add the following event procedure to 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

KeyDown, KeyUp Events — Macros

Description

Page 373: Microsoft Access Language

Microsoft Access Language Reference Página 373 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 these events.

You can't use the CancelEvent action in a KeyDown or KeyUp macro.

See Also

KeyDown, KeyUp events — event procedures.

KeyPress Event

Applies To

Bound Object Frame control, Check Box control, Combo Box control, Command Button control, Form, List Box control, Option Button control, Tab control, Toggle Button control.

Description

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 by 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, not controls on a report.

Remarks

To run a macro or event procedure when this event occurs, set the OnKeyPress property to the name of the macro or to [Event Procedure].

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 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.

Page 374: Microsoft Access Language

Microsoft Access Language Reference Página 374 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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. 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.

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 by using the BACKSPACE key, you cause a KeyPress event; if you use the DEL key, you don't.

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)

Page 375: Microsoft Access Language

Microsoft Access Language Reference Página 375 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

KeyUp (for the control)

See Also

Asc function, Change event, Chr function, Enter, Exit events, Event properties, GotFocus, LostFocus events, KeyDown, KeyUp events, KeyPreview property, NotInList event, SendKeys action, SendKeys statement.

KeyPress Event — Event Procedures

Description

To create an event procedure that runs 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 has the following arguments.

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.

Argument Description

controlname The name of the control whose KeyPress event procedure you want to run.

KeyAscii Returns a numeric ANSI key code. The KeyAscii argument is passed by reference; changing it sends a different character to the object. Setting the KeyAscii argument to 0 cancels the keystroke so that the object doesn't recognize that a key was pressed.

Page 376: Microsoft Access Language

Microsoft Access Language Reference Página 376 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

KeyPress event — macros.

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 the example, add the following event procedure to 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

KeyPress Event — Macros

Page 377: Microsoft Access Language

Microsoft Access Language Reference Página 377 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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.

See Also

KeyPress event — event procedures.

KeyPreview Property

Applies To

Form.

Description

You can use the KeyPreview property to specify whether the form-level keyboard event procedures are invoked before a control's keyboard event procedures.

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)

Page 378: Microsoft Access Language

Microsoft Access Language Reference Página 378 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the KeyPreview property by using the form's property sheet, a macro, or 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 the KeyAscii argument to 0 in the form's KeyPress event procedure, and set the KeyCode argument to 0 in the form's KeyDown and KeyUp event procedures.

If a form has no visible or enabled controls, it automatically receives all keyboard events.

See Also

KeyDown, KeyUp events, KeyPress event.

Example

In the following example, the KeyPreview property is set to True (–1) in the form's Load event procedure. This causes the form to receive keyboard events before they are received by any control. The form KeyDown event then checks the KeyCode argument value to determine if the F2, F3, or F4 keys were pushed.

Private Sub Form_Load() Me.KeyPreview = TrueEnd Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) Select Case KeyCode Case vbKeyF2 ' Process F2 key events. Case vbKeyF3 ' Process F3 key events. Case vbKeyF4 ' Process F4 key events. Case Else End SelectEnd Sub

KeyUp Event

See KeyDown, KeyUp Events.

No (Default) Only the active control receives keyboard events.

False (0)

Page 379: Microsoft Access Language

Microsoft Access Language Reference Página 379 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Kind Property

Applies To

Reference object.

Description

The Kind property indicates the type of reference that a Reference object represents.

Setting

The Kind property is read-only and can be read only from Visual Basic.

The Kind property returns the following values:

LabelAlign, TextAlign Properties

Applies To

l LabelAlign property — Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Subform/Subreport control, Text Box control, Toggle Button control.

l TextAlign property — Combo Box control, Label control Text Box control.

Description

l The LabelAlign property specifies the text alignment within attached labels on new controls.l The TextAlign property specifies the text alignment in new controls.

Setting

Value Description

Project (1) The Reference object represents a reference to a Visual Basic project.

TypeLib (0)

The Reference object represents a reference to a file that contains a type library.

Page 380: Microsoft Access Language

Microsoft Access Language Reference Página 380 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The LabelAlign property uses the following settings.

You can set the LabelAlign property by using a control's default control style or the DefaultControl method in Visual Basic.

The TextAlign property uses the following settings.

You can set the TextAlign property by using the control's property sheet, a macro, or Visual Basic.

You can also set the TextAlign property by clicking the Align Left, Center, and Align Right buttons on the Formatting (Form/Report) toolbar.

You can set the default for the TextAlign property by using a control's default control style or the DefaultControl method in Visual Basic.

Setting Description

General (Default) The label text aligns to the left.

Left The label text aligns to the left.

Center The label text is centered.

Right The label text aligns to the right.

Setting Description Visual Basic

General (Default) The text aligns to the left; numbers and dates align to the right.

0

Left The text, numbers, and dates align to the left.

1

Center The text, numbers, and dates are centered.

2

Right The text, numbers, and dates align to the right.

3

Page 381: Microsoft Access Language

Microsoft Access Language Reference Página 381 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

When created, controls have an attached label (as long as their AutoLabel property is set to Yes). Changes to the LabelAlign default control style setting affect only controls created on the current form or report.

See Also

AddColon, AutoLabel properties, LabelX, LabelY properties.

LabelX, LabelY Properties

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Subform/Subreport control, Text Box control, Toggle Button control.

Description

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 Properties dialog box in Windows Control Panel, specify the unit, such as cm or in (for example, 2 cm or 1.5 in).

You can set these properties only by using a control's default control style or the DefaultControl method in Visual Basic.

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 of 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.

Page 382: Microsoft Access Language

Microsoft Access Language Reference Página 382 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

AddColon, AutoLabel properties, LabelAlign, TextAlign properties.

LayoutForPrint Property

Applies To

Form, Report.

Description

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.

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.

Page 383: Microsoft Access Language

Microsoft Access Language Reference Página 383 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the form's or report's property sheet, a macro, or Visual Basic.

The property can be set only in form Design view or 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 that are installed on your system to be displayed on the screen. If you installed a printer, additional screen fonts may have been installed automatically.

Printer fonts are the letters, numbers, and symbols that are produced when you print a report or a form. The available fonts are those fonts that were installed as part of your printer's setup, and depend on your printer.

If you set the LayoutForPrint property to Yes, the Formatting (Form/Report) 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 when you print the form or report to let you know that it was designed for another kind of printer. If you print the form or report anyway, your printer may substitute different fonts. Similarly, Microsoft Access may substitute fonts if you change the LayoutForPrint property setting. For example, you might design a form or report with LayoutForPrint set to No, then change the setting to Yes. You can reselect the font for each control to specify the appearance of the form or report.

See Also

FontName, FontSize properties.

Left, Top Properties

Setting Description Visual Basic

Yes (Default for reports) Uses printer fonts. True (–1)

No (Default for forms) Uses screen fonts. False (0)

Page 384: Microsoft Access Language

Microsoft Access Language Reference Página 384 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

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

Description

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 positioned in 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 Properties dialog box in 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 by using a control's property sheet, a macro, or Visual Basic.

For reports, you can set these properties only by using a macro or event procedure in Visual Basic while the report is in Print Preview 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 Page Setup dialog box, available by clicking Page Setup on the File menu.

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.

See Also

Height, Width 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 NextRecord and PrintSection properties are set to False (0). The section doesn't advance to the next record, and the next section isn't printed.

Page 385: Microsoft Access Language

Microsoft Access Language Reference Página 385 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Sub Detail1_Format(Cancel As Integer, FormatCount As Integer)Const conLeftMargin = 1880' Don't advance to next record or print next section' if Left property setting is less than 1880 twips. If Me.Left < conLeftMargin Then Me.NextRecord = False Me.PrintSection = False End IfEnd Sub

LimitToList Property

Applies To

Combo Box control, Table field.

Description

You can use the LimitToList property to limit a combo box's values to the listed items.

Setting

The LimitToList property uses the following settings.

You can set the LimitToList property by using the combo box's property sheet, a macro, or Visual Basic.

For table fields, you can set this property on the Lookup tab of the Field Properties section of

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. If the entered text doesn't match a listed item, the text isn't accepted and the user must then 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)

Page 386: Microsoft Access Language

Microsoft Access Language Reference Página 386 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

table Design view for fields with the DisplayControl property set to Combo Box.

Tip Microsoft Access sets the LimitToList 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 (in the field specified in the combo box's ControlSource property), 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 by using a macro or Visual Basic event procedure that runs when the NotInList event occurs.

Note If you set the combo box's BoundColumn property to any column other than the first visible column (or if you set BoundColumn to 0), the LimitToList property is automatically set to Yes.

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, and restricts the entries to only those values.

When the LimitToList property is set to Yes and the user clicks the arrow next to the combo box, Microsoft Access selects matching values in the list as the user enters characters in the text box portion of the combo box, even if the AutoExpand property is set to No. If the user presses ENTER or moves to another control or record, the selected value appears in the combo box.

In Microsoft Access 97, combo boxes accept Null values when the LimitToList property is set to Yes or True, whether or not the list contains Null values. If you want to prevent users from entering a Null value in a combo box, set the Required property of the field in the table to which the combo box is bound to Yes.

See Also

NotInList event.

Line Method

Applies To

Report object.

Description

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]]]

Page 387: Microsoft Access Language

Microsoft Access Language Reference Página 387 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use this method only in an event procedure or a macro specified by the OnPrint or OnFormat event property for a report section, or the OnPage event property for a report.

The Line method has the following arguments.

Argument Description

object The Report object on which the line or rectangle is to be drawn.

Step A keyword that indicates the starting point coordinates are relative to the current graphics position given by the settings for the CurrentX and CurrentY properties of the object argument.

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 the Report object specified by the object argument 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 keyword 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 arguments are required.

color A Long value indicating the RGB (red-green-blue) color used to draw the line. 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.

Page 388: Microsoft Access Language

Microsoft Access Language Reference Página 388 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

CurrentX, CurrentY properties, DrawMode property, DrawStyle property, DrawWidth property, Event properties, FillColor property, FillStyle property, ForeColor property, Print event, QBColor function, RGB function, ScaleHeight, ScaleWidth properties, ScaleLeft, ScaleTop properties, ScaleMode property.

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. Paste the following code in the declarations section of the report's module, then switch to Print Preview.

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer) ' Call the Drawline procedure DrawLineEnd Sub

Sub DrawLine() Dim rpt As Report, lngColor As Long Dim sngTop As Single, sngLeft As Single Dim sngWidth As Single, sngHeight As Single

Set rpt = Reports!EmployeeReport ' Set scale to pixels.

B An option that creates a rectangle by 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.

Page 389: Microsoft Access Language

Microsoft Access Language Reference Página 389 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

rpt.ScaleMode = 3 ' Top inside edge. sngTop = rpt.ScaleTop + 5 ' Left inside edge. sngLeft = rpt.ScaleLeft + 5 ' Width inside edge. sngWidth = rpt.ScaleWidth - 10 ' Height inside edge. sngHeight = rpt.ScaleHeight - 10 ' Make color red. lngColor = RGB(255,0,0) ' Draw line as a box. rpt.Line(sngTop, sngLeft) - (sngWidth, sngHeight), lngColor, BEnd Sub

Lines Property

Applies To

Module object.

Description

The Lines property returns a string containing the contents of a specified line or lines in a standard module or a class module.

Setting

object.Lines(line, numlines)

The Lines property uses the following settings.

The Lines property is available only by using Visual Basic and is read-only.

Remarks

Lines in a module are numbered beginning with 1. For example, if you read the Lines property with a value of 1 for the line argument and 1 for the numlines argument, the Lines property returns a

Setting Description

object A Module object.

line A Long value that specifies the line number of the first line to return.

numlines A Long value that specifies the number of lines to return.

Page 390: Microsoft Access Language

Microsoft Access Language Reference Página 390 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

string containing the text of the first line in the module.

To insert a line of text into a module, use the InsertLines method.

See Also

InsertLines method.

Example

The following example deletes a specified line from a module.

Function DeleteWholeLine(strModuleName, strText As String) As Boolean Dim mdl As Module, lngNumLines As Long Dim lngSLine As Long, lngSCol As Long Dim lngELine As Long, lngECol As Long Dim strTemp As String On Error GoTo Error_DeleteWholeLine DoCmd.OpenModule strModuleName Set mdl = Modules(strModuleName) If mdl.Find(strText, lngSLine, lngSCol, lngELine, lngECol) Then lngNumLines = Abs(lngELine - lngSLine) + 1 strTemp = LTrim$(mdl.Lines(lngSLine, lngNumLines)) strTemp = RTrim$(strTemp) If strTemp = strText Then mdl.DeleteLines lngSLine, lngNumLines Else MsgBox "Line contains text in addition to '" _ & strText & "'." End If Else MsgBox "Text '" & strText & "' not found." End If DeleteWholeLine = True Exit_DeleteWholeLine: Exit Function Error_DeleteWholeLine: MsgBox Err & " :" & Err.Description DeleteWholeLine = False Resume Exit_DeleteWholeLineEnd Function

You could call this function from a procedure such as the following, which searches the module Module1 for a constant declaration and deletes it.

Sub DeletePiConst() If DeleteWholeLine("Module1", "Const conPi = 3.14") Then Debug.Print "Constant declaration deleted successfully." Else Debug.Print "Constant declaration not deleted." End IfEnd Sub

LineSlant Property

Applies To

Page 391: Microsoft Access Language

Microsoft Access Language Reference Página 391 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Line control.

Description

You use the LineSlant property to specify whether a line control slants from upper left to lower right or from upper right to lower left.

Setting

The LineSlant property uses the following settings.

You can set this property by 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.

See Also

Line method.

LinkChildFields, LinkMasterFields Properties

Applies To

Chart control, Subform/Subreport control, Unbound Object Frame control.

Description

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

Setting Description Visual Basic

\ (Default) Upper left to lower right

False (0)

/ Upper right to lower left True (–1)

Page 392: Microsoft Access Language

Microsoft Access Language Reference Página 392 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the LinkChildFields and LinkMasterFields properties for the subform, subreport, or embedded object as follows:

l The LinkChildFields property. Enter the name of one or more linking fields in the subform, subreport, or embedded object.

l The LinkMasterFields property. 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 box in the property sheet.

You can also set these properties by 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:

l Both the main form or report and the child object are based on tables, and a relationship between those tables has been defined with the Relationships command. Microsoft Access uses the fields that relate the two tables as the linking fields.

l 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.

Page 393: Microsoft Access Language

Microsoft Access Language Reference Página 393 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ListCount Property

Applies To

Combo Box control, List Box control.

Description

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

Microsoft Access sets the ListCount property to 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 by using a macro or Visual Basic. You can read this property only in Form view and Datasheet view.

Remarks

The ListCount property setting contains the total number of rows in the combo box list or list box, as determined by the control's RowSource and RowSourceType properties. If the control is based on a table or query (the RowSourceType property is set to Table/Query and the RowSource property is set to a particular table or query), the ListCount property setting contains the number of records in the table or query result set. If the RowSourceType property is set to Value List, the ListCount property setting contains the number of rows the value list specified in the RowSource property results in (this depends on the value list and the number of columns in the list box or combo box list, as set by the ColumnCount property).

If you set the ColumnHeads property to Yes, the row of column headings is included in the number of rows returned by the ListCount property. For combo boxes and list boxes based on a table or query, adding column headings adds an additional row. For combo boxes and list boxes based on a value list, adding column headings leaves the number of rows unchanged (the first row of values becomes the column headings).

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.

See Also

Column property, ListIndex property, ListRows property, ListWidth property, Selected property.

Example

The following 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

Page 394: Microsoft Access Language

Microsoft Access Language Reference Página 394 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Set ListControl = Forms!Customers!CustomerList With ListControl If .ListCount < 8 Then .ListRows = .ListCount Else .ListRows = 8 End If End WithEnd Sub

ListIndex Property

Applies To

Combo Box control, List Box control.

Description

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 minus 1. 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 by using a macro or Visual Basic. You can read this property only in Form view and Datasheet view. This property is read-only and isn't available in other views.

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 value as the ListIndex property setting.

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 by using the Selected property of the control. The Selected property is an array of values from 0 to the ListCount property value minus 1. 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.

The ItemsSelected collection also provides a way to access data in the selected rows of a list box or combo box.

See Also

ItemsSelected collection, ListCount property, ListRows property, ListWidth property, MultiSelect property, Selected property.

Page 395: Microsoft Access Language

Microsoft Access Language Reference Página 395 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ListRows Property

Applies To

Combo Box control, Table field.

Description

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. The setting for the ListRows property must be from 1 to 255.

You can set this property by using the combo box's property sheet, a macro, or Visual Basic.

For table fields, you can set this property on the Lookup tab of the Field Properties section of table Design view for fields with the DisplayControl property set to Combo Box.

Tip Microsoft Access sets the ListRows 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 set the default for this property by using a combo box's default control style or the DefaultControl method in Visual Basic.

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.

See Also

Height, Width properties, ListCount property, ListWidth property.

Example

See the ListCount property example.

ListWidth Property

Applies To

Combo Box control, Table field.

Page 396: Microsoft Access Language

Microsoft Access Language Reference Página 396 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the ListWidth property to set the width of the list box portion of a combo box.

Setting

The ListWidth property holds a value specifying the width of the list box portion of a combo box in inches or centimeters, depending on the measurement system (U.S. or Metric) selected in the Measurement System box on the Number tab of the Regional Settings Properties dialog box of Windows Control Panel. 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 by using the combo box's property sheet, a macro, or Visual Basic.

For table fields, you can set this property on the Lookup tab of the Field Properties section of table Design view for fields with the DisplayControl property set to Combo Box.

Tip Microsoft Access sets the ListWidth 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 the default for this property by using a combo box's default control style or the DefaultControl method in Visual Basic.

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 show 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.

See Also

ListRows property.

Load, Unload Events

Applies To

Form.

Description

Page 397: Microsoft Access Language

Microsoft Access Language Reference Página 397 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l The Load event occurs when a form is opened and its records are displayed.l The Unload event occurs after 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

To run a macro or event procedure when these events occur, set the OnLoad, or OnUnload property to the name of the macro or to [Event Procedure].

The Load event is caused by user actions such as:

l Starting an application.l Opening a form by clicking Open in the Database window.l Running the OpenForm action in a macro.

The Unload event is caused by user actions such as:

l Clicking a Form window's Close button or clicking Close on the File menu or a form's Control menu.

l Running the Close action in a macro.l Quitting an application by right-clicking the application's taskbar button and then clicking

Close.l Quitting Windows while an application is running.

By running a macro or an event procedure when a form's Load event occurs, you can specify default settings for controls, or display calculated data that depends on the data in the form's records.

By running a macro or 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.

When you close a form, the following events occur in this order:

Unload Deactivate Close

The Unload event occurs before the Close event. The Unload event can be canceled, but the Close event can't.

Page 398: Microsoft Access Language

Microsoft Access Language Reference Página 398 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Activate, Deactivate events, Close action, Current event, Event properties, GotFocus, LostFocus events, GoToRecord action, Open, Close events, OpenForm action, Resize event, SetFocus method.

Load, Unload Events — Event Procedures

Description

To create an event procedure that runs 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 has the following argument.

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.

Argument Description

Cancel The setting determines whether to unload the form. Setting Cancel to True (–1) prevents the form from being unloaded.

Page 399: Microsoft Access Language

Microsoft Access Language Reference Página 399 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

Load, Unload events — macros.

Example

The following example displays the current date in the form's caption when the form is loaded.

To try the example, add the following event procedure to a form:

Private Sub Form_Load() Me.Caption = DateEnd Sub

The next example prompts the user to verify that the form should close.

To try the example, add the following event procedure to a form. In Form view, close the form to display the dialog box, and then click Yes or No.

Private Sub Form_Unload(Cancel As Integer) If MsgBox("Close form?", vbYesNo) = vbYes Then Exit Sub Else Cancel = True End IfEnd Sub

Load, Unload Events — Macros

Description

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.

See Also

Page 400: Microsoft Access Language

Microsoft Access Language Reference Página 400 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Load, Unload events — event procedures.

LoadPicture Function

Description

The LoadPicture function loads a graphic into an ActiveX control.

Syntax

LoadPicture(stringexpression)

The LoadPicture function has the following argument.

Remarks

Assign the return value of the LoadPicture function to the Picture property of an ActiveX 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 by using the Set statement.

The Picture object is not a Microsoft Access object, but it is available to procedures in Microsoft Access.

Note You can't use the LoadPicture function to set the Picture property of an image control. This function works with ActiveX controls only. To set the Picture property of an image control, simply assign to it a string specifying the file name and path of the desired graphic.

Example

The following example uses the LoadPicture function to load a metafile into an ActiveX control on an Employees form.

Sub DisplayGraphic() Const strConPathToBitmaps = _

Argument Description

stringexpression The file name 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).

Page 401: Microsoft Access Language

Microsoft Access Language Reference Página 401 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

"C:\Program Files\Microsoft Office\Office\Bitmaps\Styles\"

' Declare object variables of type Picture and Control. Dim objPicture As Object, ctl As Control

' Set Control variable to refer to ActiveX control on form. Set ctl = Forms!Employees!SomeCustomControl ' Assign return value of LoadPicture to Picture object. Set objPicture = LoadPicture(strConPathToBitmaps & "Globe.wmf") ' Set Picture property of ActiveX control. Set ctl.Picture = objPictureEnd Sub

Locked Property

See Enabled, Locked Properties.

LogMessages Property

Applies To

QueryDef object, SQL-Specific query.

Description

You can use the LogMessages property in an SQL pass-through query to specify whether messages returned from an 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)

Page 402: Microsoft Access Language

Microsoft Access Language Reference Página 402 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the query's 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 SQL Server aren't stored in the messages table.

See Also

LogMessages property ("DAO Language Reference").

LostFocus Event

See GotFocus, LostFocus Events.

lpOLEObject Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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

Page 403: Microsoft Access Language

Microsoft Access Language Reference Página 403 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

unpredictable.

See Also

hWnd property.

Major Property

Applies To

Reference object.

Description

The Major property of a Reference object returns a Long value indicating the major version number of an application to which you have set a reference.

Setting

The Major property is available only by using Visual Basic and is read-only.

Remarks

The Major property returns the value to the left of the decimal point in a version number. For example, if you've set a reference to an application whose version number is 2.5, the Major property returns 2.

See Also

Minor property.

Example

See the FullPath property example.

Maximize Action

Description

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

Setting

The Maximize action doesn't have any arguments.

Page 404: Microsoft Access Language

Microsoft Access Language Reference Página 404 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Tips

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

l When you maximize a window in Microsoft Access, all other windows are also maximized when you open them or switch to them. However, pop-up forms aren't maximized. If you want a form to maintain its size when other windows are maximized, set its PopUp property to Yes. For information about how Microsoft Access maximizes windows, search the Microsoft Knowledge Base for article Q147152, "Maximizing One Form Maximizes All Forms (7.0)."

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

See Also

Maximize method, Minimize action, Restore action, SelectObject action.

Maximize Method

Applies To

DoCmd object.

Description

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 has no arguments.

See Also

DoCmd object, Maximize action, Minimize method, Restore method, SelectObject method.

MaxRecords Property

Page 405: Microsoft Access Language

Microsoft Access Language Reference Página 405 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Select query, SQL-Specific query.

Description

You can use the MaxRecords property to determine or specify the maximum number of records that will be returned by a query that returns data from an ODBC database.

Setting

The MaxRecords property setting is a Long Integer value representing the number of records that will be returned.

You can set this property by using the query's property sheet or Visual Basic.

When you set this property in Visual Basic you use the DAO MaxRecords property.

Remarks

Records are returned in the order specified by the query's ORDER BY clause.

You can use the MaxRecords property in situations where limited system resources might prohibit a large number of returned records.

See Also

MaxRecords property ("DAO Language Reference").

MDE Property

Applies To

Database object.

Description

You can use the MDE property to determine whether a database has been saved as an .mde file.

Setting

When a database is saved as an .mde file, Microsoft Access adds the MDE property to the database and sets it to the String value "T".

The MDE property can be determined only by using Visual Basic and is read-only in all views.

Important Trying to determine the MDE property for a database that hasn't been saved as an .mde file will generate run-time error 3270 (property not found). The MDE property doesn't

Page 406: Microsoft Access Language

Microsoft Access Language Reference Página 406 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

exist in a database until the database is saved as an .mde file.

Remarks

You can convert a database to an .mde file by pointing to Database Utilities on the Tools menu and clicking Make MDE File. When you save a database as an .mde file, Microsoft Access removes all editable source code, compiles all modules, and compacts the database. Your Visual Basic code still works, but the code cannot be viewed or changed. In addition, you can't add or make changes to form or report objects.

Warning Be sure to retain a copy of your original database. If you need to change any code or the design of objects in an .mde database, you must do so in the original database and then create a new .mde database. You will also need the original database in order to convert to future versions of Microsoft Access because you can't directly convert .mde files.

Saving a database as an .mde file is most appropriate when you want to prevent changes to forms or reports, or hide your Visual Basic code from the database users. You could also convert a database to an .mde file when you create your own wizards or for the front-end portion of a front-end/back-end application.

A replicated database can't be saved as an .mde file; however, once a database is saved as an .mde file, it can be replicated.

Example

The following example uses the IsItMDE function to check the MDE property for the current database:

Dim dbs As DatabaseSet dbs = CurrentDbIf IsItMDE(dbs) <> True Then ' Process custom database code.End If

Function IsItMDE(dbs As Database) As Boolean Dim strMDE As String On Error Resume Next strMDE = dbs.Properties("MDE") If Err = 0 AND strMDE = "T" Then ' This is an MDE database. IsItMDE = True Else IsITMDE = False End ifEnd Function

Me Property

Applies To

Form, Report.

Description

Page 407: Microsoft Access Language

Microsoft Access Language Reference Página 407 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the Me property in Visual Basic to refer to a form, report, (or to the form or report associated with a subform or subreport), or class module where Visual Basic code is currently running.

Setting

The Me property is available only by using Visual Basic and is read-only in all views.

Remarks

The Me property contains an object reference to the current form or report and is faster than a fully qualified object reference. For example, the following two code fragments refer to the value of the LastName control for the current record on the Employees form:

strLastName = Forms!Employees.LastName

strLastName = Me!LastName

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 you are creating generic procedures that operate on the current form, the preferred method is to pass the form to the procedure by using the Me property rather than the ActiveForm property.

You can use the Me keyword in class modules to refer to the current instance of that class. Just as you use Me in form or report class modules to retrieve a reference to the current form or report, you use Me in a class module to retrieve a reference to the current class module object.

See Also

ActiveForm property, ActiveReport property, Form, Report properties, Parent property, Screen object.

Example

The following example shows how to change the caption of a Customers form to a value supplied by the user. The ChangeCaption subroutine passes the Me property (representing the Form object) to specify the active form. Because the ChangeCaption procedure changes the caption of the active form (not a specific form), it can be called from other procedures in an application.

ChangeCaption Me, InputBox("Enter new caption " _ & "for form")

Sub ChangeCaption(frmCurrentForm As _ Form, strCaption As String)' Change caption. If TypeName(frmCurrentForm.Caption) = "Null" Then frmCurrentForm.Caption = strCaption Exit Sub End If If UCase(strCaption) _ <> UCase(frmCurrentForm.Caption) Then frmCurrentForm.Caption = strCaption

Page 408: Microsoft Access Language

Microsoft Access Language Reference Página 408 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

End IfEnd Sub

MenuBar Property

Applies To

Application object, Form, Report.

Description

You can use the MenuBar property to specify the menu bar to use for a database, form, or report. You create these menu bars by using the Customize subcommand of the Toolbars command on the View menu.

You can also use the MenuBar property to specify the menu bar macro that will be used to display a custom menu bar for a database, form, or report.

Note In previous versions of Microsoft Access, you created a custom menu bar by setting the MenuBar property to the name of a menu bar macro. You then created macro groups containing the commands for the menus on this menu bar. This functionality is still supported in Microsoft Access 97. However, it is strongly recommended that you create custom menu bars with the new Customize dialog box, available by clicking Toolbars on the View menu.

Setting

Enter the name of the menu bar you want to display. If you leave the MenuBar property setting blank, Microsoft Access displays the built-in (default) menu bar or the application's global menu bar. If you set the MenuBar property to a value that is not the name of an existing menu bar or menu bar macro, the form or report will not have a menu bar (the default menu bar will not be shown).

You can set this property by using the object's property sheet, a macro, or Visual Basic.

In Visual Basic, set this property by using a string expression that is the name of the menu bar you want to display.

To display the built-in menu bar or global menu bar for a database, form, or report by using a macro or Visual Basic, set the property to a zero-length string (" ").

Remarks

When you use the MenuBar property with forms and reports, Microsoft Access displays the specified menu bar when the form or report is opened. This menu bar is displayed whenever the form or report has the focus.

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 will be displayed in place of the database's custom menu bar whenever the form or report has the focus. When the form or report loses the focus, the custom menu bar for the database is displayed.

Page 409: Microsoft Access Language

Microsoft Access Language Reference Página 409 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note You can switch between a database's custom menu bar and the built-in menu bar by pressing CTRL+F11.

See Also

AddMenu action, AllowFullMenus property, Application object, ShortcutMenuBar property, StartupMenuBar property, Toolbar property.

Example

The following example sets the MenuBar property to a menu bar named CustomerMenu:

Forms!Customers.MenuBar = "CustomerMenu"

To display the built-in menu bar for the form or the application global menu bar, you set the MenuBar property to a zero-length string (" ").

Forms!Customers.MenuBar = ""

Minimize Action

Description

You can use the Minimize action to reduce the active window to a small title bar at the bottom of the Microsoft Access window.

Setting

The Minimize action doesn't have 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

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

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

l 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 RunCommand action to

Page 410: Microsoft Access Language

Microsoft Access Language Reference Página 410 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

carry out either of these commands from a macro.l 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.

See Also

Maximize action, Minimize method, OpenForm action, Restore action, RunCommand action, SelectObject action.

Minimize Method

Applies To

DoCmd object.

Description

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 has no arguments.

See Also

DoCmd object, Maximize method, Minimize action, OpenForm method, Restore method, SelectObject method.

MinMaxButtons Property

Applies To

Form.

Description

You can use the MinMaxButtons property to specify whether the Maximize and Minimize buttons will be visible on a form.

Setting

The MinMaxButtons property uses the following settings.

Page 411: Microsoft Access Language

Microsoft Access Language Reference Página 411 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set these properties by 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 a short title bar at the bottom of the Microsoft Access window.

To display the 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.

See Also

BorderStyle property, CloseButton property, ControlBox property, Maximize action, Minimize action, Modal property, PopUp property.

Minor Property

Setting Description Visual Basic

None The Maximize and Minimize buttons aren't visible.

0

Min Enabled

Only the Minimize button is visible. 1

Max Enabled

Only the Maximize button is visible. 2

Both Enabled

(Default) Both the Minimize and Maximize buttons are visible.

3

Page 412: Microsoft Access Language

Microsoft Access Language Reference Página 412 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Reference object.

Description

The Minor property of a Reference object returns a Long value indicating the minor version number of the application to which you have set a reference.

Setting

The Minor property is available only by using Visual Basic and is read-only.

Remarks

The Minor property returns the value to the right of the decimal point in a version number. For example, if you've set a reference to an application whose version number is 2.5, the Minor property returns 5.

See Also

Major property.

Modal Property

Applies To

Form.

Description

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)

Page 413: Microsoft Access Language

Microsoft Access Language Reference Página 413 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the form's property sheet, a macro, or Visual Basic.

Remarks

When you open a modal form, other windows in Microsoft Access are disabled until you close the form (although you can switch to windows in other applications). 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 a form will have. 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:

l Open it in Form view from the Database window.l Open it in Form view by using a macro or Visual Basic.l Switch from Design view to Form view.

When the form is modal, you can't switch to Datasheet view from Form view, although you can switch to Design view and then to Datasheet view.

The form isn't modal in Design view or Datasheet view, and also isn't modal if you switch from Datasheet view to Form view.

Note You can use the Dialog setting of the Window Mode action argument of the OpenForm action to open a form with its Modal and PopUp properties set to Yes.

See Also

BorderStyle property, CloseButton property, ControlBox property, MinMaxButtons property, OpenForm action, PopUp property.

Module Object

Description

A Module object refers to a standard module or a class module.

Remarks

Microsoft Access includes class modules which are not associated with any object, and form modules and report modules, which are associated with a form or report.

No (Default) The form opens as a non-modal form in Form view.

False (0)

Page 414: Microsoft Access Language

Microsoft Access Language Reference Página 414 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To determine whether a Module object represents a standard module or a class module from code, check the Module object's Type property.

The Modules collection contains all open Module objects, regardless of their type. Modules in the Modules collection can be compiled or uncompiled.

To return a reference to a particular standard or class Module object in the Modules collection, use any of the following syntax forms.

The following example returns a reference to a standard Module object and assigns it to an object variable:

Dim mdl As ModuleSet mdl = Modules![Utility Functions]

Note that the brackets enclosing the name of the Module object are necessary only if the name of the Module includes spaces.

The next example returns a reference to a form Module object and assigns it to an object variable:

Dim mdl As ModuleSet mdl = Modules!Form_Employees

To refer to a specific form or report module, you can also use the Form or Report object's Module property:

Forms!formname.Module

The following example also returns a reference to the Module object associated with an Employees form and assigns it to an object variable:

Dim mdl As ModuleSet mdl = Forms!Employees.Module

Once you've returned a reference to a Module object, you can set or read its properties and

Syntax Description

Modules!modulename

The modulename argument is the name of the Module object.

Modules("modulename")

The modulename argument is the name of the Module object.

Modules(index) The index argument is the numeric position of the object within the collection.

Page 415: Microsoft Access Language

Microsoft Access Language Reference Página 415 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

apply its methods.

Properties

Application property, CountOfDeclarationLines property, CountOfLines property, Lines property, Parent property, ProcBodyLine property, ProcCountLines property, ProcOfLine property, ProcStartLine property, Type property.

Methods

AddFromFile method (Module object), AddFromString method, CreateEventProc method, DeleteLines method, Find method, InsertLines method, InsertText method, ReplaceLine method.

Events

Initialize event, Terminate event.

See Also

Modules collection.

Example

The following example returns a reference to a Module object in the Modules collection and prints the number of lines of code in the module:

Function LinesInModule(strModuleName As String) As Long Dim mdl As Module

On Error GoTo Error_LinesInModule ' Open module. DoCmd.OpenModule strModuleName ' Return reference to Module object. Set mdl = Modules(strModuleName) ' Return number of lines in module. LinesInModule = mdl.CountOfLines

Exit_LinesInModule: Exit Function

Error_LinesInModule: MsgBox Err & ": " & Err.Description ' If function fails, return -1. LinesInModule = -1 Resume Exit_LinesInModuleEnd Function

Module Property

Applies To

Form, Report.

Description

You can use the Module property to specify a form module or report module.

Page 416: Microsoft Access Language

Microsoft Access Language Reference Página 416 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The Module property is available only by using Visual Basic and is read-only in all views.

Note The Module property also returns a reference to a specified Module object.

Remarks

Use the Module property to access the properties and methods of a Module object associated with a Form or Report object.

The setting of the HasModule property of a form or report determines whether it has an associated module. If the HasModule property is False, the form or report does not have an associated module. When you refer to the Module property of that form or report while in design view, Microsoft Access creates the associated module and sets the HasModule property to True. If you refer to the Module property of a form or report at run-time and the object has its HasModule property set to False, an error will occur.

You could use this property with any of the properties and methods of the module object.

See Also

HasModule property, InsertLines method, Module object, Modules collection, Type property.

Example

The following example uses the Module property to insert the Beep method in a form's Open event.

Dim strFormOpenCode As StringDim mdl As Module

Set mdl = Forms!MyForm.ModulestrFormOpenCode = "Sub Form_Open(Cancel As Integer)" _ & vbCrLf & "Beep" & vbCrLf & "End Sub" With mdl .InsertText strFormOpenCode End With

Modules Collection

Description

The Modules collection contains all open standard modules and class modules in a Microsoft Access database.

Remarks

You can enumerate through the Modules collection by using the For Each...Next statement. To determine whether an individual Module object represents a standard module or a class module, check the Module object's Type property.

Page 417: Microsoft Access Language

Microsoft Access Language Reference Página 417 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

All open modules are included in the Modules collection, whether they are uncompiled, are compiled, are in break mode, or contain the code that's running.

The Modules collection belongs to the Microsoft Access Application object.

Individual Module objects in the Modules collection are indexed beginning with zero.

Properties

Application property, Count property, Item property (collections), Item property (ObjectFrame control), Parent property.

See Also

Module object.

Example

See the Module object example.

MouseDown, MouseUp Events

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Form section, Image control, Label control, List Box control, Option Button control, Option Group control, Page, Rectangle control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

l The MouseDown event occurs when the user presses a mouse button.l The MouseUp event occurs when the user releases a mouse button.

Notes

l The MouseDown and MouseUp events apply only to forms, form sections, and controls on a form, not controls on a report.

l 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

To run a macro or event procedure when these events occur, set the OnMouseUp or OnMouseDown property to the name of the macro or to [Event Procedure].

Page 418: Microsoft Access Language

Microsoft Access Language Reference Página 418 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 or record selector 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.

The following apply to both MouseDown and MouseUp events:

l 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.

l 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.

See Also

Click event, DblClick event, Enter, Exit events, Event properties, GotFocus, LostFocus events, MouseMove event.

MouseDown, MouseUp Events — Event Procedures

Description

To create an event procedure that runs 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 have the following arguments.

Page 419: Microsoft Access Language

Microsoft Access Language Reference Página 419 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Argument Description

controlname The name of the control whose MouseDown or MouseUp event procedure you want to run.

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 The bit mask for the left mouse button.

acRightButton The bit mask for the right mouse button.

acMiddleButton The bit mask for the middle mouse button.

Page 420: Microsoft Access Language

Microsoft Access Language Reference Página 420 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Argument Description

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 The bit mask for the SHIFT key.

acCtrlMask The bit mask for the CTRL key.

acAltMask The bit mask for the ALT key.

X, Y The x and y coordinates for the current location of the mouse pointer. The X and Y arguments are always expressed in

Page 421: Microsoft Access Language

Microsoft Access Language Reference Página 421 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 an 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. . .End If

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.

See Also

MouseDown, MouseUp events — macros.

Example

The following example shows how you can find out which mouse button caused a MouseDown event.

To try the example, add the following event procedure to 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." End If If Button = acRightButton Then MsgBox "You pressed the right button." End If If Button = acMiddleButton Then

twips.

Page 422: Microsoft Access Language

Microsoft Access Language Reference Página 422 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

MsgBox "You pressed the middle button." End IfEnd Sub

MouseDown, MouseUp Events — Macros

Description

To run a macro when the MouseDown or MouseUp event occurs, set the OnMouseDown or OnMouseUp 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.

See Also

MouseDown, MouseUp events — event procedures.

MouseMove Event

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Form section, Image control, Label control, List Box control, Option Button control, Option Group control, Page, Rectangle control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

The MouseMove event occurs when the user moves the mouse.

Notes

l The MouseMove event applies only to forms, form sections, and controls on a form, not controls on a report.

l 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.

Page 423: Microsoft Access Language

Microsoft Access Language Reference Página 423 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

To run a macro or event procedure when this event occurs, set the OnMouseMove property to the name of the macro or to [Event Procedure].

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.

Notes

l 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).

l 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 event procedure in response to pressing and releasing the mouse buttons, you use the MouseDown and MouseUp events.

See Also

Click event, DblClick event, Enter, Exit events, Event properties, GotFocus, LostFocus events, MouseDown, MouseUp events.

MouseMove Event — Event Procedures

Description

To create an event procedure that runs 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 has the following arguments.

Page 424: Microsoft Access Language

Microsoft Access Language Reference Página 424 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Argument Description

controlname The name of the control whose MouseMove event procedure you want to run.

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 The bit mask for the left mouse button.

acRightButton The bit mask for the right mouse button.

acMiddleButton The 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

Page 425: Microsoft Access Language

Microsoft Access Language Reference Página 425 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 an 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. . .End If

you need to test for the Shift argument, you can use one of the following intrinsic constants as bit masks:

Constant Description

acShiftMask The bit mask for the SHIFT key.

acCtrlMask The bit mask for the CTRL key.

acAltMask The bit mask for the ALT key.

X, Y The x and y coordinates of the current location of the mouse pointer. The X and Y arguments are always expressed in twips.

Page 426: Microsoft Access Language

Microsoft Access Language Reference Página 426 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

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.

See Also

MouseMove event — macros.

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 the example, add the following event procedure to 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

Me!Coordinates.Caption = X & ", " & Y ' Use bit masks to determine state of SHIFT key and left button. intShiftDown = Shift And acShiftMask intLeftButton = Button And acLeftButton ' 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 IfEnd Sub

MouseMove Event — Macros

Page 427: Microsoft Access Language

Microsoft Access Language Reference Página 427 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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.

See Also

MouseMove event — event procedures.

MousePointer Property

Applies To

Screen object.

Description

You can use the MousePointer property together with the Screen object to specify or determine the type of mouse pointer currently displayed.

Setting

The setting for the MousePointer property is an Integer value representing one of the following pointers.

Setting Description

0 (Default) The shape is determined by Microsoft Access

1 Normal Select (Arrow)

3 Text Select (I-Beam)

Page 428: Microsoft Access Language

Microsoft Access Language Reference Página 428 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note Setting the MousePointer property to an integer other than one that appears in the preceding table will cause the property to be set to 0.

You can set the MousePointer property only by using Visual Basic.

Remarks

The MousePointer property affects the appearance of the mouse pointer over the entire screen. Some custom controls have a MousePointer property that, if set, will specify how the mouse pointer is displayed when it's positioned over the control.

You could use the MousePointer property to indicate that your application is busy by setting the property to 11 to display an hourglass icon. You can also read the MousePointer property to determine what's being displayed. This could be useful if you wanted to prevent a user from clicking a command button while the mouse pointer is displaying an hourglass icon.

Setting the MousePointer property to 11 is the same as passing the True (–1) argument to the Hourglass method of the DoCmd object. Conversely, passing the True argument to the Hourglass method also sets the MousePointer property to 11.

MouseUp Event

See MouseDown, MouseUp Events.

MoveLayout, NextRecord, PrintSection Properties

Applies To

Report.

Description

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:

7 Vertical Resize (Size N, S)

9 Horizontal Resize (Size E, W)

11 Busy (Hourglass)

Page 429: Microsoft Access Language

Microsoft Access Language Reference Página 429 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l The MoveLayout property specifies whether Microsoft Access should move to the next printing location on the page.

l The NextRecord property specifies whether a section should advance to the next record.l The PrintSection property specifies whether a section should be printed.

Setting

The MoveLayout property uses the following settings.

The NextRecord property uses the following settings.

The PrintSection property uses the following settings.

To set these properties, specify a macro or event procedure for a section's OnFormat property.

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.

Setting Description

True (Default) The section advances to the next record.

False The section doesn't advance to the next record.

Setting Description

True (Default) The section is printed.

False The section isn't printed.

Page 430: Microsoft Access Language

Microsoft Access Language Reference Página 430 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Page 431: Microsoft Access Language

Microsoft Access Language Reference Página 431 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

Event properties, Format event, Left, Top properties, NewRowOrCol property.

MoveSize Action

Description

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

Setting

The MoveSize action has the following arguments.

True False False Leave a blank space without skipping a record.

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.

Action argument

Description

Right The new horizontal position of the window's upper-left corner, measured from the left edge of its containing window. Enter the position in the Right box in the Action Arguments section of the Macro window.

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

Page 432: Microsoft Access Language

Microsoft Access Language Reference Página 432 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 on the Number tab of the Regional Settings Properties dialog box in 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

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

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

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

See Also

MoveSize method, Resize event, Restore action, SelectObject action.

MoveSize Method

Applies To

DoCmd object.

Description

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

Width The window's new width.

Height The window's new height.

Page 433: Microsoft Access Language

Microsoft Access Language Reference Página 433 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DoCmd.MoveSize [right][, down][, width][, height]

The MoveSize method has the following arguments.

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.

See Also

DoCmd object, MoveSize action, Resize event, Restore method, SelectObject method.

Example

The following example moves the active window and changes its height, but leaves its width unchanged:

DoCmd.MoveSize 1440, 2400, , 2000

MsgBox Action

Description

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

Argument Description

right A numeric expression.

down A numeric expression.

width A numeric expression.

height A numeric expression.

Page 434: Microsoft Access Language

Microsoft Access Language Reference Página 434 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 has the following arguments.

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 second section, with a blank line between them.

Enter the following in the Message argument:

Action argument

Description

Message The text in the message box. Enter the message text in the Message box in the Action Arguments section of the Macro window. You can type up to 255 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 (sound the beep tone) or No (don't sound the beep tone). 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.

Page 435: Microsoft Access Language

Microsoft Access Language Reference Página 435 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

Note If the Office Assistant is visible, the message is displayed in the Assistant's balloon instead of in a separate message box.

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.

See Also

CancelEvent action, ValidationRule, ValidationText properties.

MultiRow Property

Applies To

Tab control.

Description

You can use the MultiRow property to specify or determine whether a tab control can display more than one row of tabs.

Setting

The MultiRow property uses the following settings.

You can set the MultiRow property by using the control's property sheet, a macro, or Visual Basic.

You can also set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

Remarks

When the MultiRow property is set to True, the number of rows is determined by the width and

Setting Description Visual Basic

Yes Multiple rows are allowed. True (–1)

No (Default) Multiple rows aren't allowed. False (0)

Page 436: Microsoft Access Language

Microsoft Access Language Reference Página 436 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

number of tabs. The number of rows may change if the control is resized or if additional tabs are added to the control.

When the MultiRow property is set to False and the width of the tabs exceeds the width of the control, navigation buttons appear on the right side of the tab control. You can use the navigation buttons to scroll through all the tabs on the tab control.

See Also

Page object, Pages collection, Style property, TabFixedHeight, TabFixedWidth properties.

MultiSelect Property

Applies To

List Box control.

Description

You can use the MultiSelect property to specify whether a user can make multiple selections in a list box on a form and how the multiple selections can be made.

Setting

The MultiSelect property uses the following settings.

You can set the MultiSelect property by using the list box's property sheet, a macro, or Visual Basic.

Setting Description Visual Basic

None (Default) Multiple selection isn't allowed. 0

Simple Multiple items are selected or deselected by clicking them with the mouse or pressing the SPACEBAR.

1

Extended Multiple items are selected by holding down SHIFT and clicking them with the mouse or by holding down SHIFT and pressing an arrow key to extend the selection from the previously selected item to the current item. You can also select items by dragging with the mouse. Holding down CTRL and clicking an item selects or deselects that item.

2

Page 437: Microsoft Access Language

Microsoft Access Language Reference Página 437 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property can be set only in form Design view.

Remarks

You can use the ListIndex property to return the index number 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. When there are multiple selections in a list box, the value of the list box control will always be Null.

If the MultiSelect property is set to Extended, requerying the list box clears any selections made by the user.

See Also

Column property, ItemsSelected collection, ListIndex property, Selected property.

Name Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Form section, Image control, Label control, Line control, List Box control, Module object, Modules collection, Option Button control, Option Group control, Page, Page Break control, Rectangle control, Reference object, Reference object (Extensibility Object Model), Report, Report section, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

You can use the Name property to specify or determine the string expression that identifies the name of a form, report, section, control, or Reference object.

Setting

A valid name must conform to the object-naming rules for Microsoft Access. 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 right-clicking it 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 by 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.

Page 438: Microsoft Access Language

Microsoft Access Language Reference Página 438 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note For a Reference object, this property is read-only in all views.

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.

See Also

Name property ("DAO Language Reference"), Screen object.

NavigationButtons Property

Applies To

Form.

Description

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)

Page 439: Microsoft Access Language

Microsoft Access Language Reference Página 439 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by 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, last, or blank (new) record. The record number box displays the number of the current record. The total number of records is displayed next to the navigation buttons. You can enter a number in the record number box to move to a particular record.

If you remove the navigation buttons from a form and want to create your own means of navigation for the form, you can create custom navigation buttons and add them to the form.

See Also

BorderStyle property, RecordSelectors property, ScrollBars property.

NewCurrentDatabase Method

Applies To

Application object.

Description

You can use the NewCurrentDatabase method to create a new database in the Microsoft Access window. You can use this method to create a new database from another application that is controlling Microsoft Access through Automation, formerly called 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 has the following arguments.

No The form doesn't have navigation buttons or a record number box.

False (0)

Argument Description

application The Application object.

Page 440: Microsoft Access Language

Microsoft Access Language Reference Página 440 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The NewCurrentDatabase method enables you to create a new Microsoft Access database from another application through Automation. Once you have created an instance of Microsoft Access from another application, you must also create a new database. 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.

See Also

CloseCurrentDatabase method, OpenCurrentDatabase method.

Example

The following example creates a new Microsoft Access database from another application through Automation, and 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 ActiveX component. 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.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.8") ' Open database in Microsoft Access window. appAccess.NewCurrentDatabase strDB ' Get Database object variable. Set dbs = appAccess.CurrentDb ' Create new table. Set tdf = dbs.CreateTableDef("Contacts") ' Create field in new table. Set fld = tdf. _

dbname A string expression that is the name of a new database file, including the path name and the file name extension. If your network supports it, you can also specify a network path in the following form:

\\Server\Share\Folder\Filename.mdb

Page 441: Microsoft Access Language

Microsoft Access Language Reference Página 441 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

CreateField("CompanyName", dbText, 40) ' Append Field and TableDef objects. tdf.Fields.Append fld dbs.TableDefs.Append tdf Set appAccess = NothingEnd Sub

Note From some applications, such as Microsoft Visual Basic, 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.

NewRecord Property

Applies To

Form.

Description

You can use the NewRecord property to determine whether the current record is a new record.

Setting

The NewRecord property uses the following settings.

The NewRecord property is read-only in Form view and Datasheet view. It isn't available in Design view. This property is available only by using a macro 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.

See Also

CurrentRecord property.

Example

The following example shows how to use the NewRecord property to determine if the current

Setting Description

True (–1) The current record is new.

False (0) The current record isn't new.

Page 442: Microsoft Access Language

Microsoft Access Language Reference Página 442 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

record is a new record. The NewRecordMark procedure sets the current record to the variable intnewrec. If the record is new, a message is displayed notifying the user of this. You could run this procedure when the Current event for a form occurs.

Sub NewRecordMark(frm As Form) Dim intnewrec As Integer

intnewrec = frm.NewRecord If intnewrec = True Then MsgBox "You're in a new record." _ & "@Do you want to add new data?" _ & "@If not, move to an existing record." End IfEnd Sub

NewRowOrCol Property

Applies To

Form section, Report section.

Description

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 or multiple-column form. 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 doesn't 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 Page Setup dialog box (available by clicking Page Setup on the File menu) and the available space on the page.

0

Page 443: Microsoft Access Language

Microsoft Access Language Reference Página 443 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

You can set this property by using the section's property sheet, a macro, or Visual Basic.

You can set the NewRowOrCol property only in form Design view or report Design view.

Remarks

The following items are some sample settings for a group header section in a multiple-column report. Make sure Down, Then Across is selected under Column Layout on the Columns tab of the Page Setup dialog box.

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

Sample setting Result

Before Section The group header is printed at the top of a new column.

Page 444: Microsoft Access Language

Microsoft Access Language Reference Página 444 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Sections in a form or report are normally printed vertically down a page. The default Column Layout option is Across, Then Down. You can print the sections in multiple columns across a page by clicking Down, Then Across under Column Layout on the Columns tab of the Page Setup dialog box.

If you set the NewRowOrCol property to Before Section, the vertical or horizontal orientation of the page affects how the section appears when printed. If you click Across, Then Down under Column Layout on the Columns tab of the Page Setup dialog box, Microsoft Access starts printing the section at the beginning of a new row; if you click Down, Then Across, Microsoft Access starts printing the section at the beginning of a new column.

See Also

ForceNewPage property.

Example

The following example returns the NewRowOrCol property setting and assigns it to the intGetVal variable.

Dim intGetVal As IntegerintGetVal = Me.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 settings under Column Layout on the Columns tab of the Page Setup dialog box and the values of their NewRowOrCol properties. Note that the Width box under Column Size on the Columns tab must be set to the actual width of the field. Also, the Before Section setting of the NewRowOrCol property requires a page header section greater than zero for the Down, Then Across option to function correctly.

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.

l Column Layout — Across, Then Down

l Grid Settings — Number of Columns set to 4

l NewRowOrCol property setting for group header section — Before & After

Head1

l Column Layout — Down, Then Across

l Grid Settings — Number of Columns set to 4

l NewRowOrCol property setting for group header section — Before Section

Head1 Head2 Head3 Head4

Page 445: Microsoft Access Language

Microsoft Access Language Reference Página 445 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

NewValues Property

Applies To

Table.

Description

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.

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

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

Setting Description

Increment (Default) AutoNumber field values increment by 1 for new records.

Page 446: Microsoft Access Language

Microsoft Access Language Reference Página 446 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property in the table's property sheet in table Design view by clicking the General tab in the Field Properties section.

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.

NextRecord Property

See MoveLayout, NextRecord, PrintSection Properties.

NoData Event

Applies To

Report.

Description

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

To run a macro or event procedure when this event occurs, set the OnNoData property to the name of the macro or to [Event Procedure].

If the report isn't bound to a table or query (by using the report's RecordSource property), the NoData event doesn't occur.

This event occurs after the Format events for the report, but before the first Print event.

This event doesn't 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.

See Also

Random AutoNumber field values are assigned a random Long Integer value for new records.

Page 447: Microsoft Access Language

Microsoft Access Language Reference Página 447 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Event properties, Format event, HasData property, Page event, Print event, Retreat event.

NoData Event — Event Procedures

Description

To create an event procedure that runs 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 has the following argument.

See Also

NoData event — macros.

Example

The following example shows how to cancel printing a report when it has no data. A message box notifying the user that the printing has been canceled is also displayed.

To try this example, add the following event procedure to a report. Try running the report when it contains no data.

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 = TrueEnd Sub

Argument Description

Cancel The setting determines whether to print the report. Setting the Cancel argument to True (–1) prevents the report from printing. You can also use the CancelEvent method of the DoCmd object to cancel printing the report.

Page 448: Microsoft Access Language

Microsoft Access Language Reference Página 448 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

NoData Event — Macros

Description

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.

See Also

NoData event — event procedures.

NotInList Event

Applies To

Combo Box control.

Description

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

To run a macro or event procedure when this event occurs, set the OnNotInList property to the name of the macro or to [Event Procedure].

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 isn't in the list and attempt to move to another control or save the record. The event occurs after all the Change events for the combo box.

When the AutoExpand property is set to Yes, Microsoft Access selects matching values in the list as the user enters characters in the text box portion of the combo box. If the characters the user types match the first characters of a value in the list (for example, the user types "Smith" and "Smithson" is a value in the list), the NotInList event will not occur when the user moves to another control or saves the record. However, the characters that Microsoft Access adds to the

Page 449: Microsoft Access Language

Microsoft Access Language Reference Página 449 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

characters the user types (in the example, "son") are selected in the text box portion of the combo box. If the user wants the NotInList event to fire in such cases (for example, the user wants to add the new name "Smith" to the combo box list), the user can enter a SPACE, BACKSPACE, or DEL character after the last character in the new value.

When the LimitToList property is set to Yes and the combo box list is dropped down, Microsoft Access selects matching values in the list as the user enters characters in the text box portion of the combo box, even if the AutoExpand property is set to No. If the user presses ENTER or moves to another control or record, the selected value appears in the combo box. In this case, the NotInList event will not fire. To allow the NotInList event to fire, the user should not drop down the combo box list.

See Also

BeforeUpdate, AfterUpdate events, Change event, LimitToList property.

NotInList Event — Event Procedures

Description

To create an event procedure that runs 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, Response As Integer)

The NotInList event procedure has the following arguments.

Argument Description

controlname The name of the control whose NotInList event procedure you want to run.

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.

Page 450: Microsoft Access Language

Microsoft Access Language Reference Página 450 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Response The setting indicates how the NotInList event was handled. The Response argument can be one of the following intrinsic 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

Page 451: Microsoft Access Language

Microsoft Access Language Reference Página 451 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

NotInList event — macros.

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 combo box's LimitToList property to Yes. To populate the combo box, set the combo box's RowSourceType property 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 event procedure to 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.

by requerying the combo box. Microsoft Access then rechecks the string against the combo box list, and saves the value in the NewData argument in the field the combo box is bound to. If the string is not in the list, then Microsoft Access displays an error message.

Page 452: Microsoft Access Language

Microsoft Access Language Reference Página 452 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 IfEnd 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 — 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.

NotInList Event — Macros

Description

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.

See Also

NotInList event — event procedures.

Nz Function

Description

You can 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

Page 453: Microsoft Access Language

Microsoft Access Language Reference Página 453 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Nz(variant[, valueifnull])

The Nz function has the following arguments.

If the value of the variant argument 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 valueifnull argument is included, then the Nz function will return the value specified by that argument if the variant argument is Null.

If the value of variant isn't 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")

Argument Description

variant A variable of data type Variant.

valueifnull Optional (unless used in a query). 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 you use the Nz function in an expression in a query without using the valueifnull argument, the results will be empty in the fields that contain null values

Page 454: Microsoft Access Language

Microsoft Access Language Reference Página 454 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 the use of 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 function provides the string to be returned if varFreight is Null.

varResult = Nz(varFreight, "No Freight Charge")

See Also

Is operator, IsEmpty function, IsNull 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 object variable pointing to Orders form. Set frm = Forms!Orders ' Return Control object 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 varResultEnd Sub

Object Properties

Applies To

Form object, Module object, Report object.

Description

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, in the following ways:

l Click an object in the Database window, and then click the Properties button on the

Page 455: Microsoft Access Language

Microsoft Access Language Reference Página 455 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Database toolbar.l Click an object in the Database window, and then click Properties on the View menu.l Right-click an object in the Database window, and then click Properties on the shortcut

menu.

You can also specify or determine the Object properties by using Visual Basic.

Note You can only enter or edit the Description and 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 following Object properties are available from the Database window.

Property Description

Name This is the name of the object and contains the setting from the object's Name property.

Type This is the object's 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 setting for the object's Description property. For tables and 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 you click Details on the View menu.

Created This is the date that the object was created. For tables and queries, this property is the same as the DateCreated property.

Page 456: Microsoft Access Language

Microsoft Access Language Reference Página 456 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

Containers collection ("DAO Language Reference"), DateCreated, LastUpdated properties ("DAO Language Reference"), Description property, Description property ("DAO Language Reference"), Document object ("DAO Language Reference"), Documents collection ("DAO Language Reference"), Name property, Name property ("DAO Language Reference"), Owner property ("DAO Language Reference").

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 StringDim strObjectName As StringDim strMsg As String

strMsg = "Enter object type (e.g., Forms, Scripts, " _ & "Modules, 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

Modified This is the date that the object was last modified. For tables and 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 can be replicated in a database replica.

If you set the Hidden attribute to True (by selecting the Hidden check box), the object won't appear in the Database window. To display hidden objects in the Database window, click Options on the Tools menu, click the View tab, and then select the Hidden Objects check box. The icons for hidden objects will be dimmed in the Database window. You can then turn the Hidden attribute off, making the objects visible in the Database window.

Page 457: Microsoft Access Language

Microsoft Access Language Reference Página 457 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' PrintObjectProperties subroutine.PrintObjectProperties strObjectType, strObjectName

Sub PrintObjectProperties(strObjectType As String, strObjectName _ As String) Dim dbs As Database, ctr As Container, doc As Document Dim intI As Integer Dim strTabChar As String Dim prp As Property

Set dbs = CurrentDb strTabChar = vbTab ' Set Container object variable. Set ctr = dbs.Containers(strObjectType) ' Set Document object variable. Set doc = ctr.Documents(strObjectName) doc.Properties.Refresh ' Print the object name to Debug window. Debug.Print doc.Name ' Print each Object property to Debug window. For Each prp in doc.Properties Debug.Print strTabChar & prp.Name & " = " & prp.Value NextEnd Sub

Object Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

You can use the Object property in Visual Basic to return a reference to the Automation object that is associated with a linked or embedded OLE object in a control. By using this reference, you can access the properties or invoke the methods of the OLE object.

Setting

The Object property returns a reference to an Automation object. You can use the Set statement to assign this Automation object to an object variable. The type of object reference returned depends on which application created the OLE object.

The Object property setting is read-only in all views.

Remarks

When you embed or link an OLE object in a Microsoft Access form, you can set properties that determine the type of object and the behavior of the container control. However, you can't directly set or read the OLE object's properties or apply its methods, as you can when performing Automation. The Object property returns a reference to an Automation object that represents the linked or embedded OLE object. By using this reference, you can change the OLE object by setting or reading its properties or applying its methods. For example, Microsoft Excel is an ActiveX component that supports Automation. If you've embedded a Microsoft Excel worksheet in a Microsoft Access form, you can use the Object property to set a reference to the Worksheet object associated with that worksheet. You can then use any of the properties and methods of the Worksheet object.

Page 458: Microsoft Access Language

Microsoft Access Language Reference Página 458 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

For information on which properties and methods an Automation object supports, see the documentation for the application that was used to create the OLE object.

Example

The following example uses the Object property of an unbound object frame named OLE1. Customer name and address information is inserted in an embedded Microsoft 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 placeholder 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 object property of control to variable. Set objWord = Me!OLE1.Object.Application.Wordbasic ' Assign customer address to variables. strCustomer = Me!CompanyName strAddress = Me!Address strCity = Me!City & ", " If Not IsNull(Me!Region) Then strRegion = Me!Region Else strRegion = Me!Country End If ' Activate ActiveX control. Me!OLE1.Action = acOLEActivate With objWord .StartOfDocument ' Go to first placeholder. .LineDown 2 ' Highlight placeholder text. .EndOfLine 1 ' Insert customer name. .Insert strCustomer ' Go to next placeholder. .LineDown .StartOfLine ' Highlight placeholder text. .EndOfLine 1 ' Insert address. .Insert strAddress ' Go to last placeholder. .LineDown .StartOfLine ' Highlight placeholder text. .EndOfLine 1 ' Insert City and Region. .Insert strCity & strRegion .FilePrint .FileClose End With Set objWord = NothingEnd Sub

ObjectPalette Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Command Button control, Image

Page 459: Microsoft Access Language

Microsoft Access Language Reference Página 459 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

control, Toggle Button control, Unbound Object Frame control.

Description

The ObjectPalette property specifies the palette in the application used to create:

l An OLE object contained in a bound object frame, chart, or unbound object frame.l A bitmap or other graphic that is loaded into a command button, image control, or toggle

button by using the Picture property.

Setting

Microsoft Access sets the value of the ObjectPalette property to a String data type containing the palette information. You can use this setting to set the value of the PaintPalette property for a form or report.

For the following objects, views, and controls, the ObjectPalette property setting is read-only. This property setting is unavailable for these controls in other views.

You can use the setting of this property only in a macro or Visual Basic.

If the application associated with the OLE object, bitmap, or other graphic doesn't have an associated palette, the ObjectPalette property is set to an zero-length string.

Remarks

The setting of the ObjectPalette property makes the palette of the application associated with the OLE object, bitmap, or other graphic contained in a control 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

Object View Control

Forms Form Design view and Form view

Command button, chart, image control, toggle button, and unbound object frame.

Form view Bound object frame.

Reports Report Design view

Command button, chart, image control, toggle button, and unbound object frame. This property setting is unavailable for a bound object frame in all views on a report.

Page 460: Microsoft Access Language

Microsoft Access Language Reference Página 460 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 PaintPalette and PaletteSource properties let you specify which color palette a form should use when displaying graphics.

See Also

PaintPalette property, PaletteSource property, Picture property.

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's PaintPalette property to the palette 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.ObjectPaletteEnd Sub

Sub SunsetPicture_Enter() Me.PaintPalette = Me!SunsetPicture.ObjectPaletteEnd Sub

ObjectVerbs Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

You can use the ObjectVerbs property in Visual Basic to determine the list of verbs an OLE object supports.

Setting

The ObjectVerbs property setting is a zero-based string array.

Page 461: Microsoft Access Language

Microsoft Access Language Reference Página 461 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 points to the Object 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.

See Also

Action property, ObjectVerbsCount property, Verb property.

Example

The following example returns the verbs supported by the OLE object in the OLE1 control and displays each verb in a message box.

Sub GetVerbList(frm As Form, OLE1 As Control) Dim intX As Integer, intNumVerbs As Integer Dim strVerbList As String

' Update verb list. With frm!OLE1 .Action = acOLEFetchVerbs intNumVerbs = .ObjectVerbsCount For intX = 0 To intNumVerbs - 1 strVerbList = strVerbList & .ObjectVerbs(intX) & "; " Next intX End With

' Display verbs in message box. MsgBox Left(strVerbList, Len(strVerbList) - 2)End Sub

Page 462: Microsoft Access Language

Microsoft Access Language Reference Página 462 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ObjectVerbsCount Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

You can use the ObjectVerbsCount property in Visual Basic to determine the number of verbs supported by 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.

See Also

Action property, ObjectVerbs property, Verb property.

Example

See the ObjectVerbs property example.

ODBCConnectStr Property

Applies To

SQL-Specific query.

Description

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.

Page 463: Microsoft Access Language

Microsoft Access Language Reference Página 463 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the query's 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) by 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

For more information about accessing data in ODBC databases, see Chapter 18, "Accessing External Data," in Building Applications with Microsoft Access 97.

See Also

Connect property ("DAO Language Reference"), ODBCTimeout property, ODBCTimeout property ("DAO Language Reference").

ODBCTimeout Property

Applies To

Action query, Crosstab query Parameter query, Select query, SQL-Specific query.

Description

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 time-out error occurs.

Page 464: Microsoft Access Language

Microsoft Access Language Reference Página 464 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the query's property sheet or Visual Basic.

Remarks

When you're using an ODBC database, such as 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.

For more information about accessing data in ODBC databases, see Chapter 18, "Accessing External Data," in Building Applications with Microsoft Access 97.

See Also

ODBCTimeout property ("DAO Language Reference"), QueryTimeout property ("DAO Language Reference").

OldValue Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Image control, List Box control, Option Button control, Option Group control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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 by using a macro or Visual Basic.

The OldValue property can be assigned to a variable by using the following syntax:

OriginalValue = Forms!Customers!AmountPaid.OldValue

Remarks

Microsoft Access uses the OldValue property to store the original value of a bound control. 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 undo any changes to text box controls on a form:

Page 465: Microsoft Access Language

Microsoft Access Language Reference Página 465 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Sub btnUndo_Click() Dim ctlTextbox As Control For Each ctlTextbox in Me.Controls If ctlTextbox.ControlType = acTextBox Then ctlTextbox.Value = ctl.OldValue End If Next ctlEnd Sub

If the control hasn't been edited, this code has no effect. When you move to another record, the record source 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.

See Also

BeforeUpdate, AfterUpdate events, ControlSource property, RecordSource property, Value 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. This procedure could be called from the BeforeUpdate event of the control that contains data you want to validate.

Sub Validate_Field() Dim curNewValue As Currency Dim curOriginalValue As Currency Dim curChange As Currency, strMsg As String curNewValue = Forms!Products!UnitPrice curOriginalValue = Forms!Products!UnitPrice.OldValue curChange = Abs(curNewValue - curOriginalValue) If curChange > (curOriginalValue * .1) Then strMsg = "Change is more than 10% of original unit price. " _ & "Restoring original unit price." MsgBox strMsg, vbExclamation, "Invalid change" Forms!Products!UnitPrice = curOriginalValue End IfEnd Sub

OLEClass Property

Applies To

ActiveX control, Chart control, Unbound Object Frame control.

Description

You can use the OLEClass property to obtain a description of the kind of OLE object contained in a chart control or an unbound object frame.

Setting

Page 466: Microsoft Access Language

Microsoft Access Language Reference Página 466 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property is set automatically in the control's 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.

Note If you are using Automation (formerly called OLE Automation) and need to specify a name to refer to the OLE object, use the Class property.

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 whereas 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.

See Also

Class property.

OLEData Property

Applies To

ActiveX control, Unbound Object Frame control.

Description

You can use the OLEData property to copy data from one unbound object frame to another or from one ActiveX control to another.

Setting

controlname.OLEData

The OLEData property uses the following settings.

The OLEData property is available only by using Visual Basic. For ActiveX controls, the OLEData

Setting Description

controlname Required. The name of the an unbound object frame control.

OLEData Required. The data contained in an unbound object frame or ActiveX control.

Page 467: Microsoft Access Language

Microsoft Access Language Reference Página 467 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

property of one ActiveX control can be set to the OLEData property of another ActiveX control only in Design view.

Remarks

You can use this property to display data in an unbound object frame based on the data contained in another unbound object frame.

When you set the OLEData property of an ActiveX control to the OLEData property of another ActiveX control, the first ActiveX control becomes another instance of the second ActiveX control. For example, the result of the following property assignment is to change the TreeView control into a Calendar control:

Me!MyTreeViewControl.OLEData = Me!MyCalendarControl.OLEData

See Also

PictureData property.

OLEType Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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 Constant

Linked The control contains a linked object. All the object's data is managed by the application that created it.

acOLELinked

Embedded The control contains an embedded object. All the object's data is managed by Microsoft Access.

acOLEEmbedded

Page 468: Microsoft Access Language

Microsoft Access Language Reference Página 468 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Action property, OLETypeAllowed 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.

Sub InsertObject_Click() Dim conUserCancelled As Integer

' Error message returned when user cancels. conUserCancelled = 2001 On Error GoTo ButtonErr If OLE1.OLEType = acOLENone Then ' No OLE object created. ' Display Insert Object dialog box. OLE1.Action = acOLEInsertObjDlg End If Exit Sub

ButtonErr: If Err = conUserCancelled Then ' Display message. MsgBox "You clicked the Cancel button; no object was created." End If Resume NextEnd Sub

OLETypeAllowed Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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.

None The control doesn't contain an OLE object.

acOLENone

Page 469: Microsoft Access Language

Microsoft Access Language Reference Página 469 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the OLETypeAllowed property by using the control's property sheet, a macro, or Visual Basic. You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

Note For unbound object frames and charts, 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.

See Also

OLEType property.

Example

See the Action property example.

You can set the KeepTogether property for a group by using the Sorting And Grouping box, a macro, or Visual Basic.

In Visual Basic, you set the KeepTogether property for a group in report Design view or the Open event procedure of a report by using the GroupLevel property.

Remarks

To set the KeepTogether property for a group to a value other than No, you must set the GroupHeader or GroupFooter property or both 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 for a group to Whole Group and the group is too large to fit on one page, Microsoft

Setting Description Constant

Linked The control can contain only a linked object.

acOLELinked

Embedded The control can contain only an embedded object.

acOLEEmbedded

Either (Default) The control can contain either a linked or an embedded object.

acOLEEither

Page 470: Microsoft Access Language

Microsoft Access Language Reference Página 470 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Access will ignore the setting for that group. Similarly, if you set this property to With First Detail and either the group header or detail record is too large to fit on one page, the setting will be ignored.

If the KeepTogether property for a section is set to No and the KeepTogether property for a group is set to Whole Group or With First Detail, the KeepTogether property setting for the section is ignored.

See Also

CreateGroupLevel function, GroupHeader, GroupFooter properties, GroupInterval property, GroupLevel property, GroupOn property, GrpKeepTogether property, KeepTogether property — sections, SortOrder property.

Example

See the GroupInterval property example.

Open, Close Events

Applies To

Form, Report.

Description

l 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.

l The Close event occurs when a form or report is closed and removed from the screen.

Remarks

To run a macro or event procedure when these events occur, set the OnOpen or OnClose property to the name of the macro or to [Event Procedure].

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 activate a form that's already open — 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. However, the Activate event does occur in these situations.

When you open a form based on an underlying query, Microsoft Access runs the underlying query for the form before it runs the Open macro or event procedure. However, when you open a report based on an underlying query, Microsoft Access runs the Open macro or event procedure before

Page 471: Microsoft Access Language

Microsoft Access Language Reference Página 471 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

it runs the underlying query for the report. This enables the user to specify criteria for the report before it opens — 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 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.

See Also

Activate, Deactivate events, Event properties, GotFocus, LostFocus events, GoToRecord action, Load, Unload events, Resize event, SetFocus method.

Open, Close Events — Event Procedures

Description

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( )

Page 472: Microsoft Access Language

Microsoft Access Language Reference Página 472 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Private Sub Report_Close( )

The Open event procedure has the following argument.

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 form or to the appropriate control or record by 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", acToolbarYesEnd Sub

See Also

DoCmd object, GoToControl method, GoToRecord method, Open, Close events — macros, SetFocus method.

Example

The following example shows how you can cancel the opening of a form when the user clicks a No button. A message box prompts the user to enter order details. If the user clicks No, the Order Details form isn't opened.

To try the example, add the following event procedure to a form.

Private Sub Form_Open(Cancel As Integer) Dim intReturn As Integer intReturn = MsgBox("Enter order details now?", vbYesNo) Select Case intReturn Case vbYes DoCmd.OpenForm "Order Details" ' Open Order Details form. Case vbNo MsgBox "Remember to enter order details by 5 P.M." Cancel = True ' Cancel Open event. End SelectEnd Sub

Argument Description

Cancel The setting determines if the opening of the form or report occurs. Setting the Cancel argument to True (–1) cancels the opening of the form or report.

Page 473: Microsoft Access Language

Microsoft Access Language Reference Página 473 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Open, Close Events — Macros

Description

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 to cancel the Close event. 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.

See Also

Open, Close events — event procedures.

OpenArgs Property

Applies To

Form.

Description

You can use the OpenArgs property to determine the string expression specified by the openargs argument of the OpenForm method that opened a form.

Setting

This property is available only by using a macro or by using Visual Basic with the OpenForm method of the DoCmd object. This property setting is read-only in all views.

Remarks

To use the OpenArgs property, open a form by using the OpenForm method of the DoCmd object, 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

Page 474: Microsoft Access Language

Microsoft Access Language Reference Página 474 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

focus to move to a specific client record when the form opens, you can set the OpenArgs property to the client's 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.

See Also

DoCmd object, Open, Close events, OpenForm method.

Example

The following example uses the OpenArgs property to open the Employees form to a specific employee record and demonstrates how the OpenForm method sets the OpenArgs property. You can run this procedure as appropriate — for example, when the AfterUpdate event occurs for a custom dialog box used to enter new information about an employee.

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 IfEnd 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 IfEnd Sub

OpenCurrentDatabase Method

Applies To

Application object.

Description

You can use the OpenCurrentDatabase method to open an existing database as the current database. You can use this method to open a database from another application that is

Page 475: Microsoft Access Language

Microsoft Access Language Reference Página 475 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

controlling Microsoft Access through Automation, formerly called 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 has the following arguments.

Remarks

The OpenCurrentDatabase method enables you to open a Microsoft Access database from another application through 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 to open the database in exclusive mode. If you omit this argument, the database will open in shared mode.

Note Don't confuse the OpenCurrentDatabase method with the DAO OpenDatabase method. The OpenCurrentDatabase method opens a database in the Microsoft Access window. The DAO OpenDatabase method returns a Database object variable that represents a particular database, but doesn't actually open that database in the Microsoft Access window.

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 file name extension. If your network supports it, you can also specify a network path in the following form:

\\Server\Share\Folder\Filename.mdb

exclusive Optional. A Boolean value that specifies whether you want to open the database in exclusive mode. The default value is False, which specifies that the database should be opened in shared mode.

Page 476: Microsoft Access Language

Microsoft Access Language Reference Página 476 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

CloseCurrentDatabase method, NewCurrentDatabase method, OpenDatabase method ("DAO Language Reference").

Example

The following example opens a Microsoft Access database from another application through 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 ActiveX component. 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.Dim appAccess As Access.Application

Sub DisplayForm() Const strConPathToSamples = _ "C:\Program Files\MSOffice\Access\Samples\"

Dim strDB As String

' Initialize string to database path. strDB = strConPathToSamples & "Northwind.mdb" ' Create new instance of Microsoft Access. Set appAccess = _ CreateObject("Access.Application.8") ' 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, 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.

OpenForm Action

Description

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 that the form displays.

Setting

The OpenForm action has the following arguments.

Page 477: Microsoft Access Language

Microsoft Access Language Reference Página 477 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 in 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 results of the filter.

Page 478: Microsoft Access Language

Microsoft Access Language Reference Página 478 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Action argument

Description

(continued)Where Condition

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.

Notes

l 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.

l If you leave this argument blank,

Page 479: Microsoft Access Language

Microsoft Access Language Reference Página 479 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

This action is similar to clicking the Open button or Design button in the Database window after selecting a form on 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 use Normal for the Window Mode argument, the form opens in the mode specified by these property settings. If you use 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 by 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.

The filter and WHERE condition you apply become the setting of the form's Filter property.

See Also

ApplyFilter action, Close action, Open, Close events, OpenArgs property, OpenForm method, SelectObject action, SetValue action, WHERE clause ("SQL Language Reference").

OpenForm Method

Microsoft Access opens the form in the data entry mode set by the form's AllowEdits, AllowDeletions, AllowAdditions, and DataEntry properties.

Window Mode

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

Page 480: Microsoft Access Language

Microsoft Access Language Reference Página 480 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

DoCmd object.

Description

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 has the following arguments.

(continued)

Argument Description

formname A string expression that's 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.

Argument Description

view One of the following intrinsic constants:

acDesignacFormDSacNormal (default)acPreview

acNormal opens the form in Form view.

Page 481: Microsoft Access Language

Microsoft Access Language Reference Página 481 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

filtername A string expression that's the valid name of a query in the current database.

wherecondition A string expression that's a valid SQL WHERE clause without the word WHERE.

datamode One of the following intrinsic constants:

acFormAddacFormEditacFormPropertySettings (default)acFormReadOnly

If you leave this argument blank (the default constant, acFormPropertySettings, is assumed), Microsoft Access opens the form in the data mode set by the form's AllowEdits, AllowDeletions, AllowAdditions, and DataEntry properties.

windowmode One of the following intrinsic constants:

acDialogacHiddenacIconacWindowNormal (default)

If you leave this argument blank, the default constant(acWindowNormal) 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.

Page 482: Microsoft Access Language

Microsoft Access Language Reference Página 482 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Close method, DoCmd object, Open, Close events, OpenArgs property, OpenForm action, SelectObject method.

Example

The following 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 Action

Description

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 has the following arguments.

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 the openargs argument, and then use the FindRecord method to move the focus to the record for the client with the specified name.

This argument is available only in Visual Basic.

Page 483: Microsoft Access Language

Microsoft Access Language Reference Página 483 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 Module Name argument and the Procedure Name argument. 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.

Similarly, to open a procedure in a class module, you must specify the module name, although the class module doesn't have to 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.

See Also

Action argument

Description

Module Name The name of the module you want to open. You can leave this argument 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 argument blank, the module opens to the Declarations section.

Page 484: Microsoft Access Language

Microsoft Access Language Reference Página 484 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

OpenModule method, RunCode action.

OpenModule Method

Applies To

DoCmd object.

Description

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 has the following arguments.

(continued)

Argument Description

modulename A string expression that's 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.

Page 485: Microsoft Access Language

Microsoft Access Language Reference Página 485 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You must include at least one of the two OpenModule action 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.

See Also

DoCmd object, OpenModule action, RunCode action.

Example

The following example opens the Utility Functions module to the IsLoaded( ) Function procedure:

DoCmd.OpenModule "Utility Functions","IsLoaded"

OpenQuery Action

Description

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 has the following arguments.

procedurename A string expression that's 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.

Action argument

Description

Page 486: Microsoft Access Language

Microsoft Access Language Reference Página 486 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If you use 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 were an action, data-definition, or pass-through query whose ReturnsRecords property is set to No.

The OpenQuery action is similar to clicking 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's 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.

See Also

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.

Page 487: Microsoft Access Language

Microsoft Access Language Reference Página 487 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

OpenQuery method, RunSQL action, SetWarnings action.

OpenQuery Method

Applies To

DoCmd object.

Description

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 has the following arguments.

(continued)

Argument Description

queryname A string expression that's 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:

acViewDesignacViewNormal (default)acViewPreview

Page 488: Microsoft Access Language

Microsoft Access Language Reference Página 488 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

DoCmd object, RunSQL method.

Example

The following 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 Action

Description

You can use the OpenReport action to open a report in Design view or Print Preview, or to print

If the queryname argument is the name of a select, crosstab, union, or pass-through query whose ReturnsRecords property is set to –1, acViewNormal displays the query's result set. If the queryname argument refers to an action, data-definition, or pass-through query whose ReturnsRecords property is set to 0, acViewNormal runs the query.

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

datamode One of the following intrinsic constants:

acAddacEdit (default)acReadOnly

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

Page 489: Microsoft Access Language

Microsoft Access Language Reference Página 489 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

the report immediately. You can also restrict the records that are printed in the report.

Setting

The OpenReport action has the following arguments.

(continued)

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.

Action argument

Description

(continued)Report Name

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 (print the report immediately), Design, or Print Preview in the View box. The default is Print.

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.

Page 490: Microsoft Access Language

Microsoft Access Language Reference Página 490 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The Print setting for the View argument prints the report immediately by 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 filter and WHERE condition you apply become the setting of the report's Filter property.

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

l 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.

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 results of 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 OpenReport 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.

Page 491: Microsoft Access Language

Microsoft Access Language Reference Página 491 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l 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.

See Also

ApplyFilter action, OpenReport method, Print method, PrintOut action, WHERE clause ("SQL Language Reference").

OpenReport Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Argument Description

reportname A string expression that's 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:

acViewDesignacViewNormal (default)acViewPreview

Page 492: Microsoft Access Language

Microsoft Access Language Reference Página 492 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

DoCmd object, OpenReport action, PrintOut method.

Example

The following example prints Sales Report while using the existing query Report Filter:

DoCmd.OpenReport "Sales Report", acViewNormal, "Report Filter"

OpenTable Action

Description

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 has the following arguments.

acViewNormal prints the report immediately. If you leave this argument blank, the default constant (acViewNormal) is assumed.

filtername A string expression that's the valid name of a query in the current database.

wherecondition A string expression that's a valid SQL WHERE clause without the word WHERE.

Page 493: Microsoft Access Language

Microsoft Access Language Reference Página 493 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

This action is similar to clicking the Open button or Design button in the Database window after selecting a table on 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.

See Also

OpenTable method.

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 a 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 in 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.

Page 494: Microsoft Access Language

Microsoft Access Language Reference Página 494 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

OpenTable Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Argument Description

tablename A string expression that's 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:

acViewDesignacViewNormal (default)acViewPreview

acViewNormal opens the table in Datasheet view.

Page 495: Microsoft Access Language

Microsoft Access Language Reference Página 495 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

DoCmd object, OpenTable action.

Example

The following example opens the Employees table in Print Preview:

DoCmd.OpenTable "Employees", acViewPreview

OptionValue Property

Applies To

Check Box control, Option Button control, Toggle Button control.

Description

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.

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

datamode One of the following intrinsic constants:

acAddacEdit (default)acReadOnly

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

Page 496: Microsoft Access Language

Microsoft Access Language Reference Página 496 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 value 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 check box, a toggle button, or an option button isn't 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.

See Also

Controls collection, ControlSource property, TripleState property.

OrderBy Property

Applies To

Form, Parameter query, Report, Select query, Table.

Description

You can use the OrderBy property to specify how you want to sort records in a form, query, report, or table.

Setting

Page 497: Microsoft Access Language

Microsoft Access Language Reference Página 497 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 are sorted in ascending order. Similarly, Visual Basic sorts 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 by using the object's property sheet, a macro, or 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 by which you want to sort 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 by using Visual Basic.

Setting the OrderBy property for an open report will run the report's Close and Open event procedures.

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.

See Also

AllowFilters property, ApplyFilter action, ApplyFilter method, Filter property, Filter property ("DAO Language Reference"), FilterOn property, OrderByOn property.

OrderByOn Property

Applies To

Form, Parameter query, Report, Select query, Table.

Description

You can use the OrderByOn property to specify whether an object's OrderBy property setting is applied.

Setting

The OrderByOn property uses the following settings.

Page 498: Microsoft Access Language

Microsoft Access Language Reference Página 498 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

For reports, you can set the OrderByOn property by using the report's property sheet, a macro, or Visual Basic.

For all other objects, you can set the OrderByOn property by clicking a Sort button on the toolbar or by 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.

See Also

AllowFilters property, ApplyFilter action, ApplyFilter method, Filter property, Filter property, FilterOn property, OrderBy property.

OutputAllFields Property

Applies To

Action query, Parameter query, Select query.

Description

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 click 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 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)

Page 499: Microsoft Access Language

Microsoft Access Language Reference Página 499 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property only by using the query's property sheet.

Note The use of an asterisk (*) in an SQL statement in place of a field name is the equivalent of setting the OutputAllFields property to Yes.

Remarks

When the OutputAllFields property 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 the OutputAllFields property to Yes.

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 StringstrGetSQL = "SELECT * FROM Shippers"Forms!Form1.RecordSource = strGetSQLText1.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 enter this SQL statement in SQL view of the Query window.

SELECT * FROM Suppliers INNER JOIN ProductsON Suppliers.[SupplierID] = Products.[SupplierID]ORDER BY Suppliers.[CompanyName], Products.[ProductName];

OutputTo Action

Description

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 that have the Show box selected in the query design grid.

Page 500: Microsoft Access Language

Microsoft Access Language Reference Página 500 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 97 (*.xls), MS-DOS text (*.txt), or rich-text (*.rtf) format. You can also output to a file in HTML (*.html) format, to files in Microsoft Internet Information Server (*.htx, *.idc) format, or to a file in Microsoft ActiveX Server (*.asp) format. Files in Microsoft Internet Information Server format can also be used with Microsoft Personal Web Server.

Setting

The OutputTo action has 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 argument blank. This is a required argument. The default is Table.

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 HTML (*.html), Microsoft ActiveX Server (*.asp), Microsoft Excel (*.xls), Microsoft IIS (*.htx, *.idc), MS-DOS Text (*.txt), or Rich Text Format (*.rtf) in the box. Modules can be output only to MS-DOS text format. Microsoft Internet Information Server and Microsoft ActiveX Server formats are available only for tables, queries, and forms. If you leave this argument 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 file name extension (.asp, .htm or .html, .htx, .xls, .txt, or .rtf) for the output format you select with the Output Format argument, but it's not required. If you output to Microsoft Internet Information Server or Microsoft ActiveX Server files, Microsoft Access will always create files with the standard .htx and .idc or .asp file name extensions. If you leave the Output File argument blank, Microsoft Access prompts you for an output file name.

Page 501: Microsoft Access Language

Microsoft Access Language Reference Página 501 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 Microsoft Word.

If you output the database object to HTML format, Microsoft Access creates a file in HTML format containing the data from the object. You can use the Template File argument to specify a file to be used as a template for the .html file.

If you output the object to Microsoft Internet Information Server format, Microsoft Access creates two files:

l An .idc file, which contains information on how to connect to an ODBC data source, and an SQL statement to execute against this data source. In this case, the Microsoft Access object you're outputting contains the data defined by the SQL statement and the current Microsoft Access database is the ODBC data source

l An .htx file, which specifies how to format data returned from the SQL statement specified in the .idc file as an HTML document. You can use the Template File argument to specify an .html file to be used as a template for the .htx file.

Microsoft Internet Information Server uses the .htx and .idc files to create an .html file with the data in the Microsoft Access object you output.

Auto Start Specifies whether you want the appropriate application to start immediately after the OutputTo action runs, with the file specified by 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 Windows Notepad (for .txt files), or Microsoft Word (for .rtf files). For .html files, your default Internet browser (such as Microsoft Internet Explorer) starts. This argument is ignored for Microsoft Internet Information Server and Microsoft ActiveX Server files. If you select No, the application doesn't start. The default is No.

Template File The path and file name of a file you want to use as a template for an .html, .htx, or .asp file. The template file is a file containing HTML tags.

Page 502: Microsoft Access Language

Microsoft Access Language Reference Página 502 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

If you output the database object to Microsoft ActiveX Server format, Microsoft Access creates a file in .asp format which contains information on how to access and format the object's data. Microsoft ActiveX Server uses the .asp file to create an .html file with the data in the Microsoft Access object you output. You can use the Template File argument to specify an .html file to be used as a template for the .asp file.

The following rules apply when you use the OutputTo action to output a database object to any of the output formats except Microsoft ActiveX Server (some of these rules also apply to the Microsoft ActiveX Server format):

l 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.

l 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).

l For a text box bound to a Hyperlink field, the output file displays the hyperlink for all output formats except MS-DOS text (in this case, the hyperlink is just displayed as normal text).

l If you output the data in a form in Form view, the output file always contains the form's Datasheet view.

l 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, .txt, and .html 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 with 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.

l Subreports are included in the output file, but subforms aren't.l When you output a datasheet or form in HTML format, one .html file is created. When you

output a report in HTML format, one .html file is created for each page in the report.

Tip If you output the data in a report to an output file and the columns and rows of data in the output file don't align as in the report, the following tips may help:

l You can point to Size on the Format menu, then click To Fit to size the controls.l You should avoid overlapping controls or placing controls too close together.l You can point to Align on the Format menu, then click the appropriate command to align

the controls on the report. Controls that aren't aligned in the same row may be placed in separate rows in the output file, 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's 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 isn't 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. You can also click Save As HTML on the File menu, which runs the Publish to the Web Wizard, which you can use to output a database object to an .html file,

Page 503: Microsoft Access Language

Microsoft Access Language Reference Página 503 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

to .htx/.idc files, or to an .asp file.

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

See Also

OutputTo method, SendObject action.

OutputTo Method

Applies To

DoCmd object.

Description

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]ú[, templatefile]

The OutputTo method has the following arguments.

Argument Description

objecttype One of the following intrinsic constants:

acOutputFormacOutputModuleacOutputQueryacOutputReportacOutputTable

objectname A string expression that's the valid name of an object of the type selected by 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.

Page 504: Microsoft Access Language

Microsoft Access Language Reference Página 504 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

If you run 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.

Argument Description

outputformat One of the following intrinsic constants:

acFormatActiveXServeracFormatHTMLacFormatIISacFormatRTFacFormatTXTacFormatXLS

If you leave this argument blank, Microsoft Access prompts you for the output format.

outputfile A string expression that's 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 Microsoft Windows–based application immediately, with the file specified by the outputfile argument loaded. Use False (0) if you don't want to start the application. This argument is ignored for Microsoft Internet Information Server (.htx, .idc) files and Microsoft ActiveX Server (*.asp) files.

Page 505: Microsoft Access Language

Microsoft Access Language Reference Página 505 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

Modules can be output only in MS-DOS Text format, so if you specify acOutputModule for the objecttype argument, you must specify acFormatTXT for the outputformat argument. Microsoft Internet Information Server and Microsoft ActiveX Server formats are available only for tables, queries, and forms, so if you specify acFormatIIS or acFormatActiveXServer for the outputformat argument, you must specify acOutputTable, acOutputQuery, or acOutputForm for the objecttype 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.

See Also

DoCmd object, OutputTo action, SendObject method.

Example

The following 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 acOutputTable, "Employees", acFormatRTF, _ "Employee.rtf", True

Page Event

Applies To

Report.

Description

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

To run a macro or event procedure when this event occurs, set the OnPage property to the

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

templatefile A string expression that's the full name, including the path, of the file you want to use as a template for an HTML, HTX, or ASP file.

Page 506: Microsoft Access Language

Microsoft Access Language Reference Página 506 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

name of the macro or to [Event Procedure].

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.

See Also

Circle method, Event properties, Format event, Line method, NoData event, Page, Pages properties, Print event, PSet method, Retreat event.

Page Event — Event Procedures

Description

To create an event procedure that runs 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.

See Also

Page event — macros.

Example

The following example shows how to draw a rectangle around a report page by 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), , BEnd Sub

Page Event — Macros

Description

Page 507: Microsoft Access Language

Microsoft Access Language Reference Página 507 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Page event — event procedures.

Page Object

Description

A Page object corresponds to an individual page on a tab control.

Remarks

A Page object is a member of a tab control's Pages collection.

To return a reference to a particular Page object in the Pages collection, use any of the following syntax forms.

You can create, move, or delete Page objects and set their properties either in Visual Basic or in form Design view. To create a new Page object in Visual Basic, use the Add method of the Pages collection. To delete a Page object, use the Remove method of the Pages collection.

To create a new Page object in form Design view, right-click the tab control and then click Insert

Syntax Description

Pages!pagename The pagename argument is the name of the Page object.

Pages("pagename")

The pagename argument is the name of the Page object.

Pages(index) The index argument is the numeric position of the object within the collection.

Page 508: Microsoft Access Language

Microsoft Access Language Reference Página 508 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Page on the shortcut menu. You can also copy an existing page and paste it. You can set the properties of the new Page object in form Design view by using the property sheet.

Each Page object has a PageIndex property that indicates its position within the Pages collection. The Value property of the tab control is equal to the PageIndex property of the current page. You can use these properties to determine which page is currently selected after the user has switched from one page to another, or to change the order in which the pages appear in the control.

A Page object is also a type of Control object. The ControlType property constant for a Page object is acPage. Although it is a control, a Page object belongs to a Pages collection, rather than a Controls collection. A tab control's Pages collection is a special type of Controls collection.

Each Page object can also contain one or more controls. Controls on a Page object belong to that Page object's Controls collection. In order to work with a control on a Page object, you must refer to that control within the Page object's Controls collection.

Properties

Application property, Caption property, Column property, ControlTipText property, ControlType property, Enabled, Locked properties, Event properties, EventProcPrefix property, Height, Width properties, HelpContextID, HelpFile properties, InSelection property, IsVisible property, Left, Top properties, Name property, OldValue property, Page, Pages properties, PageIndex property, Parent property, Picture property, PictureData property, PictureType property, Properties property, Section property, ShortcutMenuBar property, StatusBarText property, Tag property, Visible property.

Methods

Requery method (Control or Form object), SetFocus method, SizeToFit method.

Events

Click event, DblClick event, MouseDown, MouseUp events, MouseMove event.

See Also

Controls collection, Pages collection.

Example

The following event procedure enumerates all the controls on each page of a tab control when the user selects that page.

To try this example, create a new form with a tab control named TabCtl0 and set its OnChange property to [Event Procedure]. Paste the following code in the form's module. Switch to Form view and click on the different tabs to enumerate their controls.

Private Sub TabCtl0_Change() Dim tbc As Control, pge As Page Dim ctl As Control

' Return reference to tab control. Set tbc = Me!TabCtl0 ' Return reference to currently selected page. Set pge = tbc.Pages(tbc.Value)

Page 509: Microsoft Access Language

Microsoft Access Language Reference Página 509 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' Enumerate controls on currently selected page. Debug.Print pge.Name & " Controls:" For Each ctl In pge.Controls Debug.Print ctl.Name Next ctl Debug.PrintEnd Sub

Page, Pages Properties

Applies To

Form, Report, Tab control.

Description

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.

l The Page property specifies the current page number when a form or report is being printed.

l The Pages 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 Visual Basic.

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 510: Microsoft Access Language

Microsoft Access Language Reference Página 510 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

PageHeader, PageFooter 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. To test this example, paste the following code into the Page Event for the Alphabetical List of Products form.

Dim intTotalPages As Integer, strMsg As StringintTotalPages = Me.PagesstrMsg = "This report contains " & intTotalPages & " pages."MsgBox strMsg

PageHeader, PageFooter Properties

Applies To

Report.

Description

You can use the PageHeader and PageFooter properties to specify whether a report's page header or page footer is 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.

="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).

Setting Description Visual Basic

Page 511: Microsoft Access Language

Microsoft Access Language Reference Página 511 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

You can set these properties by 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.

Example

The following example sets the PageHeader property for a report to Not With Rpt Hdr. To run this

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

Setting Description Visual Basic

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

Page 512: Microsoft Access Language

Microsoft Access Language Reference Página 512 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

example, type the following line in the Debug window for a report named Report1.

Reports!Report1.PageHeader = 1

PageIndex Property

Applies To

Page.

Description

You can use the PageIndex property to specify or determine the position of a Page object within a Pages collection. The PageIndex property specifies the order in which the pages on a tab control appear.

Setting

The PageIndex property setting is an Integer value between 0 and the Pages collection Count property setting minus 1.

You can set the PageIndex property by using a Page object's property sheet, a macro, or Visual Basic.

The PageIndex property can be set in any view.

Remarks

Changing the value of the PageIndex property changes the location of a Page object in the Pages collection and visually changes the order of pages on a tab control.

You can also change the order of Page objects in the Pages collection by using the Page Order dialog box available by right-clicking the tab control in Design view and then clicking Page Order.

See Also

Count property, Page object, Pages collection.

Pages Collection

Description

The Pages collection contains all Page objects in a tab control.

Remarks

The Pages collection is a special kind of Controls collection belonging to the tab control. It

Page 513: Microsoft Access Language

Microsoft Access Language Reference Página 513 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

contains Page objects, which are controls. The Pages collection differs from a typical Controls collection in that you can add and remove Page objects by using methods of the Pages collection.

To add a new Page object to the Pages collection from Visual Basic, use the Add method of the Pages collection. To remove an existing Page object, use the Remove method of the Pages collection. To count the number of Page objects in the Pages collection, use the Count property of the Pages collection.

You can also use the CreateControl method to add a Page object to the Pages collection of a tab control. To do this, you must specify the name of the tab control for the parent argument of the CreateControl function. The ControlType property constant for a Page object is acPage.

You can enumerate through the Pages collection by using the For Each...Next statement.

Individual Page objects in the Pages collection are indexed beginning with zero.

Properties

Count property, Item property (collections).

Methods

Add method (Pages collection), Remove method (Pages collection).

See Also

Page object.

Example

See the Page object example.

Painting Property

Applies To

Form, Report.

Description

You can use the Painting property to specify whether forms or reports are repainted.

Setting

The Painting property uses the following settings.

Page 514: Microsoft Access Language

Microsoft Access Language Reference Página 514 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using a macro or Visual Basic.

This property can be set and 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.)

The Painting property is automatically set to True whenever the form or report gets or loses the focus. You can set this property to False while you are working on a form or report if you don't want to see changes to the form or report or to its controls. For example, if a form has a set of controls that are automatically resized when the form is resized and you don't want the user to see each individual control move, you can turn Painting off, and then move all of the controls, then turn Painting back on.

See Also

Echo action, Hourglass action, RepaintObject action.

Example

The following example uses the Painting property to enable or disable form painting depending on whether the SetPainting variable is set to True (–1) or False (0). If form painting is turned off, Microsoft Access displays the hourglass icon while painting is turned off.

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 hourglass icon. Else DoCmd.Hourglass False ' Don't hourglass display icon. End IfEnd Function

Setting Description

True (–1) (Default) The form or report is repainted.

False (0) The form or report isn't repainted.

Page 515: Microsoft Access Language

Microsoft Access Language Reference Página 515 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

PaintPalette Property

Applies To

Form, Report.

Description

You can use the PaintPalette property to specify a palette to be used by a form or report.

Setting

You can set the PaintPalette property by using a macro or Visual Basic. The property setting must be a String data type containing the palette information.

You can set the PaintPalette property by assigning the value of the ObjectPalette property to the PaintPalette property in a macro or Visual Basic, by setting the PaletteSource property (in which case Microsoft Access automatically sets the PaintPalette property to this PaletteSource), or by setting the PaintPalette property of one form or report to the PaintPalette property of another form or report.

For a form, you can set the PaintPalette property in form Design view and Form view.

For a report, you can set the PaintPalette property in report 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). The PaintPalette property (which is available only in a macro or Visual Basic) is used to set the palette for the form or report. The PaletteSource property gives you a way to set the palette for the form or report in the property sheet by using an existing graphics file.

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 PaintPalette and PaletteSource properties let you specify which color palette a form should use when displaying graphics.

You can use the ObjectPalette property to make the palette of an application associated with an

Page 516: Microsoft Access Language

Microsoft Access Language Reference Página 516 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

OLE object, bitmap, or other graphic contained in a control on a form or report available to the PaintPalette property. 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.

See Also

ObjectPalette property, PaletteSource property, Picture property.

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's PaintPalette property to the palette 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.ObjectPaletteEnd Sub

Sub SunsetPicture_Enter() Me.PaintPalette = Me!SunsetPicture.ObjectPaletteEnd Sub

PaletteSource Property

Applies To

Form, Report.

Description

You can use the PaletteSource property to specify the palette for a form or report.

Setting

Enter the path and file name of one of the following file types:

l .dib (device-independent bitmap file)l .pal (Windows palette file)

Page 517: Microsoft Access Language

Microsoft Access Language Reference Página 517 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l .ico (Windows icon file)l .bmp (Windows bitmap file)l .wmf or .emf file, or other graphics file for which you have a graphics filter

The default setting is (Default), which specifies the palette included with Microsoft Access. If you change this setting by entering a path and file name, the property setting displays (Custom).

You can set this property by using the form's or report's property sheet, a macro, or Visual Basic.

For a form, you can set the PaletteSource property in form Design view and Form view. The property setting is unavailable in other views.

For a report, you can set the PaletteSource property only in report Design view. The property setting is unavailable in other views.

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 and PaintPalette properties let 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). The PaintPalette property (which is available only in a macro or Visual Basic) is used to set the palette for the form or report. The PaletteSource property gives you a way to set the palette for the form or report in the property sheet by using an existing graphics file.

See Also

ObjectPalette property, PaintPalette property.

Parent Property

Applies To

ActiveX control, Application object, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Controls collection, Form, Form section, Forms collection, Image control, Label control, Line control, List Box control, Module object, Modules collection, Option Button control, Option Group control, Page, Page Break control, Rectangle control, Report, Report section, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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.

Page 518: Microsoft Access Language

Microsoft Access Language Reference Página 518 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 example, you might insert an OrderDetails 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 is the name of the form.

See Also

Collection property, Form, Report properties, Forms collection, Me property, Reports collection.

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 FormDim ctl As ControlSet frm = Forms!OrdersSet ctl = frm.[Speedy Label]' Returns name of control attached to label.MsgBox "The parent control is " & ctl.Parent.NameSet ctl = frm.Speedy' Returns name of control containing control.MsgBox "The parent control is " & ctl.Parent.NameSet 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

Picture Property

Applies To

Command Button control, Form, Image control, Page, Report, Toggle Button control.

Description

Page 519: Microsoft Access Language

Microsoft Access Language Reference Página 519 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the Picture property to specify a bitmap or other type of graphic to be displayed on a command button, image control, toggle button, page on a tab control or as a background picture on a form or report. Buttons can display either a caption or a picture.

Setting

The Picture property contains (bitmap) or the path and file name of a bitmap or other type of graphic to be displayed.

You can set this property by using:

l The property sheet. Click the Build button to the right of the property box (for command buttons and toggle buttons). When you select one of the bitmap files from the Available Pictures list, the property setting is (bitmap).

l A macro.l Visual Basic. You can use a string expression that includes the path and the name of the

graphic, as in the following example:

btnShowLogo.Picture = "c:\Windows\Winlogo.bmp"

l The Picture command on the Insert menu (for image controls or background pictures on forms and reports) to select a bitmap or other type of graphic.

The default setting is (none). After the graphic is loaded into the object, the property setting is (bitmap) or the path and file name of the graphic. If you delete (bitmap) or the path and file name of the graphic from the property setting, the picture is deleted from the object and the property setting is again (none).

If the PictureType property is set to Embedded, the graphic is stored with the object.

Remarks

You can create custom bitmaps by using Microsoft Paintbrush or another application that creates bitmap files. A bitmap file must have a .bmp, .ico, or .dib extension. You can also use graphics files in the .wmf or .emf formats, or any other graphic file type for which you have a graphics filter. Forms, reports, and image controls support all graphics. Command buttons and toggle buttons only support bitmaps.

Buttons can display either a caption or a picture. If you assign both to a button, the picture will be visible, the caption won't. 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.

See Also

Caption property, HyperlinkAddress property, PictureAlignment property, PictureData property, PictureSizeMode property, PictureTiling property, PictureType property.

Page 520: Microsoft Access Language

Microsoft Access Language Reference Página 520 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

PictureAlignment Property

Applies To

Form, Image control, Report.

Description

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.

(continued)

Setting Description Visual Basic

Top Left The picture is displayed in the top-left corner of the image control, Form window, or page of a report.

0

Top Right The picture is displayed in 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 in the bottom-left corner of the image control, Form window, or page of a report.

3

Page 521: Microsoft Access Language

Microsoft Access Language Reference Página 521 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the PictureAlignment property by using a form's or report's property sheet, a macro, or Visual Basic.

You can also set the default for this property by using a control's default control style or the DefaultControl method in 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 across only 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.

See Also

Picture property, PictureData property, PicturePages property, PictureSizeMode property, PictureTiling property, PictureType property.

PictureData Property

Applies To

Command Button control, Form, Image control, Page, Report, Toggle Button control.

Description

Bottom Right

The picture is displayed in 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

Page 522: Microsoft Access Language

Microsoft Access Language Reference Página 522 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the PictureData property to copy the picture in a 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 by using Visual Basic.

Remarks

You can use this property to display different background pictures in a form, 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.

See Also

Picture property, PictureAlignment property, PicturePages property, PictureSizeMode property, PictureTiling property, PictureType 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 (0). The TimerInterval property is set to 200. Each time the Timer event occurs, the picture in the image control Visible1 is changed by 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 public variable gfrmWidth. The value of gfrmWidth is set to Me.Width in the form's open event.

Private Sub Form_Timer() Static intPic As Integer Select Case intPic Case Is = 1 Me!Visible1.PictureData = Me!Hidden1.PictureData Case Is = 2 Me!Visible1.PictureData = Me!Hidden2.PictureData Case Else End Select If intPic = 2 Then intPic = 0 intPic = intPic + 1 If (Me!Visible1.Left > gfrmWidth) Then Me!Visible1.Left = 0 Me!Visible1.Left = Me!Visible1.Left + 200End Sub

PicturePages Property

Page 523: Microsoft Access Language

Microsoft Access Language Reference Página 523 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Report.

Description

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.

You can set the PicturePages property by using a report's property sheet, a macro, or Visual Basic.

See Also

Picture property, PictureAlignment property, PictureData property, PictureSizeMode property, PictureTiling property.

PictureSizeMode Property

Applies To

Form, Report.

Description

You can use the PictureSizeMode property to specify how a picture for a form or report is sized.

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 doesn't appear on the report.

2

Page 524: Microsoft Access Language

Microsoft Access Language Reference Página 524 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The PictureSizeMode property uses the following settings.

You can set the PictureSizeMode property by using a form's or report's property sheet, a macro, or Visual Basic.

Remarks

When a small picture is used for the Picture property of a form or report, setting the PictureSizeMode property to Stretch or Zoom can cause substantial distortion of its resolution. Smaller pictures can be tiled across the entire form or report by using the PictureTiling property.

See Also

Picture property, PictureAlignment property, PictureData property, PictureTiling property, PictureType property, SizeMode property.

PictureTiling Property

Applies To

Form, Image control, Report.

Description

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

Page 525: Microsoft Access Language

Microsoft Access Language Reference Página 525 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

You can set the PictureTiling property by using the object's property sheet, a macro, or Visual Basic.

You can also set the default for this property by using a control's default control style or the DefaultControl method in 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 window, or page of a report.

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.

See Also

Picture property, PictureAlignment property, PictureData property, PicturePages property, PictureSizeMode property, PictureType property.

PictureType Property

Applies To

Command Button control, Form, Image control, Page, Report, Toggle Button control.

Description

You can use the PictureType property to specify whether Microsoft Access stores an object's

Setting Description Visual Basic

Yes The picture is tiled. True (–1)

No (Default) The picture isn't tiled.

False (0)

Page 526: Microsoft Access Language

Microsoft Access Language Reference Página 526 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

picture as a linked or an embedded object.

Setting

The PictureType property uses the following settings.

You can set the PictureType property by using the object's property sheet, a macro, or Visual Basic.

This property can be set only in form Design view or report Design view.

For controls, you can set the default for this property by using the default control style or the DefaultControl method in Visual Basic.

Remarks

When this 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 this 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 by using the object's Picture property.

For embedded pictures, the object's PictureData property stores the individual bits that make up a picture's image. For linked pictures, this property stores the path to the picture's file.

You can modify a linked picture by using a separate application and changes to the picture will appear the next time the object containing that picture is displayed in the database.

See Also

Picture property, PictureData property.

Setting Description Visual Basic

Embedded (Default) The picture is embedded in the object and becomes part of the database file.

0

Linked The picture is linked to the object. Microsoft Access stores a pointer to the location of the picture on the disk.

1

Page 527: Microsoft Access Language

Microsoft Access Language Reference Página 527 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

PopUp Property

Applies To

Form.

Description

You can use the PopUp property to specify whether a form opens as a pop-up form. For example, you set a form's PopUp property to Yes, its Modal property to Yes, and its BorderStyle property to Dialog to create a custom dialog box.

Setting

The PopUp property uses the following settings.

You can set this property by using the form's property sheet, a macro, or Visual Basic.

The PopUp property can be set only in form 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 the Modal property to Yes, the PopUp property to Yes, and the BorderStyle property to Dialog for custom dialog boxes.

Setting the PopUp property to Yes makes the form a pop-up form only when you do one of the following:

l Open it in Form view from the Database window.l Open it in Form view by using a macro or Visual Basic.l Switch from Design view to Form view.

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 isn't a pop-up form.

False (0)

Page 528: Microsoft Access Language

Microsoft Access Language Reference Página 528 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

When the PopUp property is set to Yes, you can't switch to other views from Form view, because the form's toolbar isn't available. (You can't switch a pop-up form from Form view to Datasheet view, even in a macro or Visual Basic.) You must close the form and reopen it in Design view or Datasheet view.

The form isn't a pop-up form in Design view or Datasheet view, and also isn't a pop-up form if you switch from Datasheet view to Form 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.

Tip When you maximize a window in Microsoft Access, all other windows are also maximized when you open them or switch to them. However, pop-up forms aren't maximized. If you want a form to maintain its size when other windows are maximized, set its PopUp property to Yes.

See Also

BorderStyle property, CloseButton property, ControlBox property, MinMaxButtons property, Modal property, OpenForm action.

PreviousControl Property

Applies To

Screen object.

Description

You can use the PreviousControl property with the Screen object to return a reference to the control that last received the focus.

Setting

The PreviousControl property contains a reference to the control that last had the focus. Once you establish a reference to the control, you can access all the properties and methods of the control.

This property is available only by using 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 use this property when only one control on a form has received the focus.

See Also

GotFocus, LostFocus events.

Page 529: Microsoft Access Language

Microsoft Access Language Reference Página 529 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

The following example displays a message if the control that last received the focus wasn't the txtFinalEntry text box.

Function ProcessData() As Integer Dim ctlPrevious As Control ' No previous control error. Const conNoPreviousControl = 2483 On Error GoTo Process_Err Set ctlPrevious = Screen.PreviousControl If ctlPrevious.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." ProcessData = False End IfProcess_Bye: Exit FunctionProcess_Err: If Err = conNoPreviousControl Then Me!txtFinalEntry.SetFocus MsgBox "Please enter a value to process." ProcessData = False End If Resume Process_ByeEnd Function

Primary Property

Applies To

Index.

Description

You can use the Primary property to specify the primary key field for a table. A primary key field holds data that uniquely identifies each record in a table.

Setting

The Primary property uses the following settings.

Setting Description Visual Basic

Yes The selected index is the primary key.

True (–1)

Page 530: Microsoft Access Language

Microsoft Access Language Reference Página 530 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the Primary property in three ways:

l In table Design view, select the field or fields in the order you want for the primary key and then click the Primary Key button on the toolbar.

l 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 section.

l In Visual Basic, to access the Primary property of an index, use the DAO Primary property.

Remarks

Microsoft Access automatically creates an index on the primary key field of a 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 in a multiple-field primary key determines the default sort order for the table.

If there is no primary key when you save a table's design, Microsoft Access will display a dialog box asking whether you want a primary key to be created. If you click 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 click 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.

See Also

Index object ("DAO Language Reference"), Indexed property, Primary property ("DAO Language Reference"), Unique property, Unique property ("DAO Language Reference").

Print Event

Applies To

Report section.

Description

The Print event occurs after data in a report section is formatted for printing, but before the section is printed.

Remarks

To run a macro or event procedure when this event occurs, set the OnPrint property to the name of the macro or to [Event Procedure].

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

No The selected index isn't the primary key.

False (0)

Page 531: Microsoft Access Language

Microsoft Access Language Reference Página 531 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

the 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 the data in the group header and the data in 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 the 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 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.

See Also

Event properties, Format event, FormatCount property, NoData event, Page event, Page, Pages properties, PrintCount property, Retreat event.

Print Event — Event Procedures

Description

To create an event procedure that runs 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 has the following arguments.

Argument Description

sectionname The name of the report section whose Print event procedure you want to run.

Page 532: Microsoft Access Language

Microsoft Access Language Reference Página 532 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

To cancel printing of the section, you should 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 the CancelEvent method or the Cancel argument 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.

See Also

Print event — macros.

Example

The following 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 example, add the following event procedure to a report that contains a section named CustomerDetail.

Private Sub CustomerDetail_Print(Cancel As Integer, _ PrintCount As Integer) If PrintCount > 1 Then Cancel = TrueEnd Sub

Print Event — Macros

Description

To run a macro when the Print event occurs, set the OnPrint property to the name of the macro.

Remarks

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 Microsoft Access sets the PrintCount argument to 2.

Page 533: Microsoft Access Language

Microsoft Access Language Reference Página 533 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 property 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 the CancelEvent action 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.

See Also

Print event — event procedures, PrintCount property.

Print Method

Applies To

Debug object, Report object.

Description

The Print method prints text on a Report object using the current color and font.

Syntax

object.Print [{Spc(n) | Tab(n)}][expressionlist][{;|,}]

The Print method has the following arguments.

Argument Description

object The Report object on which the text is to be printed.

Spc(n) The Visual Basic function used to insert n spaces into the printed output. Multiple use is permitted.

Page 534: Microsoft Access Language

Microsoft Access Language Reference Página 534 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can use this method only in a event procedure or macro specified by a section's OnPrint event property setting.

The expressions specified by the expressionlist argument are printed on the object starting at the position indicated by the CurrentX and CurrentY property settings.

When the expressionlist argument is printed, a carriage return is usually appended so that the next Print method begins printing on the next line. When a carriage return occurs, the CurrentY property setting is increased by the height of the expressionlist argument (the same as the value returned by the TextHeight method) and the CurrentX property is set to 0.

When a semicolon follows the expressionlist argument, no carriage return is appended, and the next Print method prints on the same line that the current Print method printed on. The CurrentX and CurrentY properties are set to the point immediately after the last character printed. If the expressionlist argument itself contains carriage returns, each such embedded carriage return sets the CurrentX and CurrentY properties as described for the Print method without a semicolon.

When a comma follows the expressionlist argument, the CurrentX and CurrentY properties are set to the next print zone on the same line.

When the expressionlist argument is printed on a Report object, lines that can't fit in the specified position don't scroll. The text is clipped to fit the object.

Tab(n) The Visual Basic function used to move the insertion point to the nth print zone before the expressionlist argument is printed. Print zones begin every 14 columns. The width of each column is an average of the width of all characters in the font size for the chosen font. Multiple use is permitted.

expressionlist The numeric or string expressions to print. If this argument is omitted, the Print method prints a blank line. Multiple expressions can be separated with a space, a semicolon (;), or a comma. A space has the same effect as a semicolon. You can also use the Spc and Tab functions to separate each pair of expressions.

{;|,} Determines the location of the insertion point for the next character printed. A semicolon means that the insertion point is placed immediately after the last character printed; a comma means that the insertion point is placed at the start of the next print zone.

Page 535: Microsoft Access Language

Microsoft Access Language Reference Página 535 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Because the Print method usually prints with proportionally spaced characters, it's important to remember that there's no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, a wide letter (such as W) occupies more than one fixed-width column, whereas a narrow letter (such as I) occupies less. You should make sure that your tabular columns are positioned far enough apart to accommodate the text you wish to print. Alternately, you can print with a fixed-pitch font (such as Courier) to ensure that each character uses only one column.

See Also

CurrentX, CurrentY properties, FontBold property, FontItalic, FontUnderline properties, FontName, FontSize properties, Scale method, ScaleHeight, ScaleWidth properties, ScaleLeft, ScaleTop properties, ScaleMode property.

Example

The following example uses the Print method to display text on a report named Report1. It uses the TextWidth and TextHeight methods to center the text vertically and horizontally.

Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer) Dim rpt As Report Dim strMessage As String Dim intHorSize As Integer, intVerSize As Integer

Set rpt = Me strMessage = "DisplayMessage" With rpt 'Set scale to pixels, and set FontName and FontSize properties. .ScaleMode = 3 .FontName = "Courier" .FontSize = 24 End With ' Horizontal width. intHorSize = Rpt.TextWidth(strMessage) ' Vertical height. intVerSize = Rpt.TextHeight(strMessage) ' Calculate location of text to be displayed. Rpt.CurrentX = (Rpt.ScaleWidth/2) - (intHorSize/2) Rpt.CurrentY = (Rpt.ScaleHeight/2) - (intVerSize/2) ' Print text on Report object. Rpt.Print strMessageEnd Sub

PrintCount Property

Applies To

Report.

Description

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

Page 536: Microsoft Access Language

Microsoft Access Language Reference Página 536 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 report 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 the 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 in the OrderAmount control is added only once to the running total:

Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer) If PrintCount = 1 Then RunningTotal = RunningTotal + OrderAmount End IfEnd Sub

In the previous example, RunningTotal can be a public variable or the name of an unbound control that is incremented each time a section is printed.

See Also

Event properties, FormatCount property, Print event.

PrintOut Action

Description

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 has the following arguments.

Action argument

Description

Page 537: Microsoft Access Language

Microsoft Access Language Reference Página 537 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

This action is similar to selecting an object and then clicking Print on the File menu. With this 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.

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's selected), or Pages (the user can specify a range of pages in the Page From and Page To arguments) in the Print Range box in the Action Arguments section of the Macro window. 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 select 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 select Pages in 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 (collate the printed copies) or No (don't collate copies). The object may print faster if this argument is set to No. The default is Yes.

Page 538: Microsoft Access Language

Microsoft Access Language Reference Página 538 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

OpenForm action, OpenQuery action, OpenReport action, OpenTable action, PrintOut method.

PrintOut Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Argument Description

printrange One of the following intrinsic constants:

acPrintAll (default)acSelectionacPages

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

pagefrom A numeric expression that's a valid page number in the active form or datasheet. This argument is required if you specify acPages for the printrange argument.

Page 539: Microsoft Access Language

Microsoft Access Language Reference Página 539 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

DoCmd object, OpenForm method, OpenModule method, OpenQuery method, OpenReport method, OpenTable method, Print method, PrintOut action.

Example

The following example prints two collated copies of the first four pages of the active form or datasheet:

DoCmd.PrintOut acPages, 1, 4, , 2

PrintSection Property

pageto A numeric expression that's 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:

acDraftacHigh (default)acLowacMedium

If you leave this argument blank, the default constant (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.

Page 540: Microsoft Access Language

Microsoft Access Language Reference Página 540 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See MoveLayout, NextRecord, PrintSection Properties.

ProcBodyLine Property

Applies To

Module object.

Description

The ProcBodyLine property returns a Long value containing the number of the line at which the body of a specified procedure begins in a standard module or a class module. The body of a procedure begins with the procedure definition, denoted by one of the following:

l A Sub statement.l A Function statement.l A Property Get statement.l A Property Let statement.l A Property Set statement.

Setting

object.ProcBodyLine(procname, prockind)

The ProcBodyLine property uses the following settings.

Setting Description

object A Module object.

procname A string expression that evaluates to the name of a procedure in the module.

Page 541: Microsoft Access Language

Microsoft Access Language Reference Página 541 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The ProcBodyLine property is available only by using Visual Basic and is read-only.

Remarks

The ProcBodyLine property returns a number that identifies the line on which the procedure definition begins. In contrast, the ProcStartLine property returns a number that identifies the line at which a procedure is separated from the preceding procedure in a module. Any comments or compilation constants that precede the procedure definition (the body of a procedure) are considered part of the procedure, but the ProcBodyLine property ignores them.

Note The ProcBodyLine property treats Sub and Function procedures similarly, but distinguishes between each type of Property procedure.

See Also

Function statement, ProcCountLines property, ProcOfLine property, ProcStartLine property, Property Get statement, Property Let statement, Property Set statement, Sub statement.

Example

The following function prints information about a specified procedure in a module to the Debug window:

Function ProcLineInfo(strModuleName As String, strProcName As String) Dim mdl As Module Dim lngStartLine As Long, lngBodyLine As Long Dim lngCount As Long, lngEndProc As Long

prockind An intrinsic constant that specifies the type of procedure. The constant may be one of the following values.

Constant Description

vbext_pk_Get A Property Get procedure.

vbext_pk_Let A Property Let procedure.

vbext_pk_Proc A Sub or Function procedure.

vbext_pk_Set A Property Set procedure.

Page 542: Microsoft Access Language

Microsoft Access Language Reference Página 542 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' Open specified Module object. DoCmd.OpenModule strModuleName ' Return reference to Module object. Set mdl = Modules(strModuleName)

' Count lines in procedure. lngCount = mdl.ProcCountLines(strProcName, vbext_pk_Proc) ' Determine start line. lngStartLine = mdl.ProcStartLine(strProcName, vbext_pk_Proc) ' Determine body line. lngBodyLine = mdl.ProcBodyLine(strProcName, vbext_pk_Proc) Debug.Print

' Print all lines in procedure preceding body line. Debug.Print "Lines preceding procedure " & strProcName & ": " Debug.Print mdl.Lines(lngStartLine, lngBodyLine - lngStartLine)

' Determine line number of last line in procedure. lngEndProc = (lngBodyLine + lngCount - 1) - Abs(lngBodyLine - lngStartLine)

' Print all lines in body of procedure. Debug.Print "Body lines: " Debug.Print mdl.Lines(lngBodyLine, (lngEndProc - lngBodyLine) + 1)End Function

You could call this function from the Northwind sample database with a procedure such as the following:

Sub GetProcInfo() ProcLineInfo "Utility Functions", "IsLoaded"End Sub

ProcCountLines Property

Applies To

Module object.

Description

The ProcCountLines property returns a Long value containing the number of lines in a specified procedure in a standard module or a class module. The procedure begins with any comments and compilation constants that immediately precede the procedure definition, denoted by one of the following:

l A Sub statement.l A Function statement.l A Property Get statement.l A Property Let statement.l A Property Set statement.

Setting

object.ProcCountLines(procname, prockind)

The ProcCountLines property uses the following settings.

Page 543: Microsoft Access Language

Microsoft Access Language Reference Página 543 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The ProcCountLines property is available only by using Visual Basic and is read-only.

Setting Description

object A Module object.

procname A string expression that evaluates to the name of a procedure in the module.

prockind An intrinsic constant that specifies the type of procedure. The constant may be one of the following values.

Constant Description

vbext_pk_Get A Property Get procedure.

vbext_pk_Let A Property Let procedure.

vbext_pk_Proc A Sub or Function procedure.

vbext_pk_Set A Property Set procedure.

Page 544: Microsoft Access Language

Microsoft Access Language Reference Página 544 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The ProcCountLines property returns the number of lines in a procedure, beginning with the line returned by the ProcStartLine property and ending with the line that ends the procedure. The procedure may be ended with End Sub, End Function, or End Property.

Note The ProcCountLines property treats Sub and Function procedures similarly, but distinguishes between each type of Property procedure.

See Also

Function statement, ProcBodyLine property, ProcOfLine property, ProcStartLine property, Property Get statement, Property Let statement, Property Set statement, Sub statement.

Example

See the ProcBodyLine property example.

ProcOfLine Property

Applies To

Module object.

Description

The ProcOfLine property returns a string containing the name of the procedure that contains a specified line in a standard module or a class module. The body of a procedure begins with the procedure definition, denoted by one of the following:

l A Sub statement.l A Function statement.l A Property Get statement.l A Property Let statement.l A Property Set statement.

Setting

object.ProcOfLine(line, pprockind)

The ProcOfLine property uses the following settings.

Page 545: Microsoft Access Language

Microsoft Access Language Reference Página 545 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Setting Description

object A Module object.

line A Long that specifies the number of a line in the module.

pprockind An Long value that indicates the type of procedure containing the line specified by the line argument. When you return the value of the ProcOfLine property, the value of the pprockind argument is set to an intrinsic constant that specifies the type of procedure the line belongs to. The constant may be one of the following values.

Constant Value Description

vbext_pk_Get 3 A Property Get procedure.

Page 546: Microsoft Access Language

Microsoft Access Language Reference Página 546 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The ProcOfLine property is available only by using Visual Basic and is read-only.

Remarks

For any given line number, the ProcOfLine property returns the name of the procedure that contains that line. Since comments and compilation constants immediately preceding a procedure definition are considered part of that procedure, the ProcOfLine property may return the name of a procedure for a line that isn't within the body of the procedure. The ProcStartLine property indicates the line on which a procedure begins; the ProcBodyLine property indicates the line on which the procedure definition begins (the body of the procedure).

Note that the pprockind argument indicates whether the line belongs to a Sub or Function procedure, a Property Get procedure, a Property Let procedure, or a Property Set procedure. To determine what type of procedure a line is in, pass a variable of type Long to the ProcOfLine property, then check the value of that variable.

Note The ProcBodyLine property treats Sub and Function procedures similarly, but distinguishes between each type of Property procedure.

See Also

Function statement, ProcBodyLine property, ProcCountLines property, ProcStartLine property, Property Get statement, Property Let statement, Property Set statement, Sub statement.

Example

The following function procedure lists the names of all procedures in a specified module:

Function AllProcs(strModuleName As String) Dim mdl As Module Dim lngCount As Long, lngCountDecl As Long, lngI As Long Dim strProcName As String, astrProcNames() As String Dim intI As Integer, strMsg As String Dim lngR As Long

' Open specified Module object. DoCmd.OpenModule strModuleName ' Return reference to Module object. Set mdl = Modules(strModuleName) ' Count lines in module. lngCount = mdl.CountOfLines ' Count lines in Declaration section in module. lngCountDecl = mdl.CountOfDeclarationLines ' Determine name of first procedure. strProcName = mdl.ProcOfLine(lngCountDecl + 1, lngR) ' Initialize counter variable.

vbext_pk_Let 1 A Property Let procedure.

vbext_pk_Proc 0 A Sub or Function procedure.

vbext_pk_Set 2 A Property Set procedure.

Page 547: Microsoft Access Language

Microsoft Access Language Reference Página 547 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

intI = 0 ' Redimension array. ReDim Preserve astrProcNames(intI) ' Store name of first procedure in array. astrProcNames(intI) = strProcName ' Determine procedure name for each line after declarations. For lngI = lngCountDecl + 1 To lngCount ' Compare procedure name with ProcOfLine property value. If strProcName <> mdl.ProcOfLine(lngI, lngR) Then ' Increment counter. intI = intI + 1 strProcName = mdl.ProcOfLine(lngI, lngR) ReDim Preserve astrProcNames(intI) ' Assign unique procedure names to array. astrProcNames(intI) = strProcName End If Next lngI strMsg = "Procedures in module '" & strModuleName & "': " _ & vbCrLf & vbCrLf For intI = 0 To UBound(astrProcNames) strMsg = strMsg & astrProcNames(intI) & vbCrLf Next intI ' Dialog box listing all procedures in module. MsgBox strMsgEnd Function

You could call this function with a procedure such as the following:

Sub GetAllProcs() AllProcs "Utility Functions"End Sub

ProcStartLine Property

Applies To

Module object.

Description

The ProcStartLine property returns a Long value identifying the line at which a specified procedure begins in a standard module or a class module. The procedure begins with any comments and compilation constants that immediately precede the procedure definition, denoted by one of the following:

l A Sub statement.l A Function statement.l A Property Get statement.l A Property Let statement.l A Property Set statement.

Setting

object.ProcStartLine(procname, prockind)

The ProcStartLine property uses the following settings.

Page 548: Microsoft Access Language

Microsoft Access Language Reference Página 548 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The ProcStartLine property is available only by using Visual Basic and is read-only.

Remarks

The ProcStartLine property returns the number of the line on which the specified procedure begins. The beginning of the procedure may include comments or compilation constants that precede the procedure definition.

To determine the line on which the procedure definition begins, use the ProcBodyLine property.

Setting Description

object A Module object.

procname A string expression that evaluates to the name of a procedure in the module.

prockind An intrinsic constant that specifies the type of procedure. The constant may be one of the following values.

Constant Description

vbext_pk_Get A Property Get procedure.

vbext_pk_Let A Property Let procedure.

vbext_pk_Proc A Sub or Function procedure.

vbext_pk_Set A Property Set procedure.

Page 549: Microsoft Access Language

Microsoft Access Language Reference Página 549 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property returns the number of the line that begins with a Sub, Function, Property Get, Property Let, or Property Set statement.

The ProcStartLine and ProcBodyLine properties can have the same value, if the procedure definition is the first line of the procedure. If the procedure definition isn't the first line of the procedure, the ProcBodyLine property will have a greater value than the ProcStartLine property.

Notes

l It may be easier to determine where a procedure begins if you have the Procedure Separator option selected. With this option selected, there is a line between the end of a procedure and the beginning of the next procedure. The first line of code (or blank line) below the procedure separator is the first line of the following procedure, which is the line returned by the ProcStartLine property. The Procedure Separator option is located on the Module tab of the Options dialog box, available by clicking Options on the Tools menu. To select the Procedure Separator check box, first select the Full Module View check box.

l The ProcStartLine property treats Sub and Function procedures similarly, but distinguishes between each type of Property procedure.

See Also

Function statement, ProcBodyLine property, ProcCountLines property, ProcOfLine property, Property Get statement, Property Let statement, Property Set statement, Sub statement.

Example

See the ProcBodyLine property example.

ProjectName Property

Applies To

Application object.

Description

You can use the ProjectName property to specify or determine the name of your Microsoft Access Application object.

Setting

The ProjectName property is a string expression that's the name of your Microsoft Access Application object. You can't set the ProjectName property to the name of an existing class of objects, for example, "application," "form," or "report." If you convert a database with a name that is the same as that of an existing class of objects, Microsoft Access will append an underscore to the name to prevent naming conflicts. For example, if the database you are converting is named "Application," the database will have a project name of "Application_" in Microsoft Access 97.

You can set the ProjectName property on the Advanced tab of the Options dialog box (available

Page 550: Microsoft Access Language

Microsoft Access Language Reference Página 550 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

by clicking Options on the Tools menu) or by using the SetOption method in Visual Basic. For example:

Application.SetOption "Project Name", "MyAccessProject"

Remarks

When you create a new database, Microsoft Access sets the ProjectName property to the database file name without the ".mdb" extension. Changing the database file name has no effect on the existing ProjectName property setting.

When you set the ProjectName property, the name of your Application object appears in the References dialog box, available in the Module window by clicking References on the Tools menu.

When you change the setting of the ProjectName property, your project will no longer be in a compiled state. To recompile the project, you must close and reopen your database and then click Compile And Save All Modules on the Debug menu.

From another application, such as Microsoft Excel, you can use the project name as part of the fully qualified name of an item in a Microsoft Access project by using the syntax projectname.Application.Forms!formname. For example, to refer to the LastName field on the Employees form in the Northwind sample database from Microsoft Excel, you set a reference to the Northwind database and then use the following reference:

Dim strLstName As StringstrLastName = Northwind.Application.Forms!Employees!LastName

You can create a reference to a Microsoft Access database by selecting the project name (the Application object) in the References dialog box, available in the Module window by clicking References on the Tools menu. Once you select the project name, it also appears in the Project/Library list in the Object Browser.

See Also

Application object, GetOption, SetOption methods.

Properties Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Control object, Form, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Page, Page Break control, Rectangle control, Report, Report section, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

You can use the Properties property to return a reference to a control's Properties collection object.

Page 551: Microsoft Access Language

Microsoft Access Language Reference Página 551 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

controlname.Properties[.method or property]

The Properties property uses the following settings.

The Properties property is available only by using Visual Basic.

Remarks

The Properties collection object is the collection of all the properties related to a control. You can refer to individual members of the collection by using the member object's index or a string expression that is the name of the member object. The first member object in the collection has an index value of 0 and the total number of member objects in the collection is the value of the Properties collection's Count property minus 1.

See Also

Count property ("DAO Language Reference"), Item property (collections).

Example

The following procedure uses the Properties property to print all the properties associated with the controls on a form to the Debug window. To run this code, place a command button named cmdListProperties on a form and paste the following code into the form's Declarations section. Click the command button to print the list of properties in the Debug window.

Sub cmdListProperties_Click() ListControlProps MeEnd Sub

Sub ListControlProps(frm As Form) Dim ctl As Control, prp As Property

Setting Description

controlname Required. The name of the control whose Properties collection object you want to reference.

Properties Required. When used without specifying a method or property, returns the Properties collection object.

method or property

A method or property of the Properties collection object. The Item property (collections) is the default property for the Properties collection object.

Page 552: Microsoft Access Language

Microsoft Access Language Reference Página 552 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

On Error GoTo props_err For Each ctl In frm.Controls Debug.Print ctl.Properties("Name") For Each prp In ctl.Properties Debug.Print vbTab & prp.Name & " = " & prp.Value Next prp Next ctl

props_bye: Exit Sub

props_err: If Err = 2187 Then Debug.Print vbTab & prp.Name & " = Only available at design time." Resume Next Else Debug.Print vbTab & prp.Name & " = Error Occurred: " & Err Resume Next End IfEnd Sub

PrtDevMode Property

Applies To

Form, Report.

Description

You can use the PrtDevMode property to set or return printing device mode information specified for a form or report in the Print 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.

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 string with a maximum of 32 bytes that specifies the name of the device the driver supports — for example, "HP LaserJet IIISi" if the Hewlett-Packard LaserJet IIISi is the specified printer. Each printer driver has a unique string.

Page 553: Microsoft Access Language

Microsoft Access Language Reference Página 553 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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.

Member Description

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.

Page 554: Microsoft Access Language

Microsoft Access Language Reference Página 554 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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. If you set this member to 0 or 256, 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

Page 555: Microsoft Access Language

Microsoft Access Language Reference Página 555 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

Page 556: Microsoft Access Language

Microsoft Access Language Reference Página 556 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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. The values are –4 (high), –3 (medium), –2 (low), and –1 (draft).

Page 557: Microsoft Access Language

Microsoft Access Language Reference Página 557 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Color An Integer. For a color printer, specifies whether the output is printed in color. The values are 1 (color) and 2 (monochrome).

Duplex An Integer. For a printer capable of duplex printing, specifies whether the output is printed on both sides of the paper. The values are 1 (simplex), 2 (horizontal), and 3 (vertical).

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.

Page 558: Microsoft Access Language

Microsoft Access Language Reference Página 558 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the PrtDevMode property using Visual Basic.

This property setting is read/write in Design view and read-only in other views.

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 string with a maximum of 16 characters that specifies the size of paper to use; for example, "Letter" or "Legal."

Pad A Long value that is used to pad out spaces, characters, or values for future versions.

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 (screen or printer).

PH A Long value that specifies the height, in pixels, of the visible device surface (screen or printer).

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.

Page 559: Microsoft Access Language

Microsoft Access Language Reference Página 559 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Caution Printer drivers can add device-specific data immediately following the 94 bytes of the DEVMODE structure. For this reason, it is important that the DEVMODE data outlined above not exceed 94 bytes.

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 using the DC_PAPERS, DC_PAPERSIZE, and DC_PAPERNAMES values to call the DeviceCapabilities function.

Before setting the value of the TTOption member, applications should find out how a printer driver can use TrueType fonts by using the DC_TRUETYPE value to call the DeviceCapabilities function.

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

Page 560: Microsoft Access Language

Microsoft Access Language Reference Página 560 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Values for the PaperSize Member

DM_DUPLEX &H0001000

DM_YRESOLUTION &H0002000

DM_TTOPTION &H0004000

DM_COLLATE &H0008000

DM_FORMNAME &H0010000

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)

Page 561: Microsoft Access Language

Microsoft Access Language Reference Página 561 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

11 A5 (148 x 210 mm)

12 B4 (250 x 354 mm)

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 (17 x 22 in.)

25 D size sheet (22 x 34 in.)

26 E size sheet (34 x 44 in.)

27 Envelope DL (110 x 220 mm)

Page 562: Microsoft Access Language

Microsoft Access Language Reference Página 562 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Values for the DefaultSource Member

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

Page 563: Microsoft Access Language

Microsoft Access Language Reference Página 563 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Values for the TTOption 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

Page 564: Microsoft Access Language

Microsoft Access Language Reference Página 564 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

PrtDevNames property, PrtMip 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 * 94End Type

Type type_DEVMODE strDeviceName As String * 16 intSpecVersion As Integer intDriverVersion As Integer intSize As Integer intDriverExtra As Integer lngFields As Long intOrientation As Integer intPaperSize As Integer intPaperLength As Integer intPaperWidth As Integer intScale As Integer intCopies As Integer intDefaultSource As Integer intPrintQuality As Integer intColor As Integer intDuplex As Integer intResolution As Integer intTTOption As Integer intCollate As Integer strFormName As String * 16 lngPad As Long lngBits As Long lngPW As Long lngPH As Long lngDFI As Long lngDFr As LongEnd Type

Value Meaning

1 Print TrueType fonts as graphics. This is the default for dot-matrix printers.

2 Download TrueType fonts as soft fonts (fonts that are loaded into the printer's memory for rendering). 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.

Page 565: Microsoft Access Language

Microsoft Access Language Reference Página 565 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Sub CheckCustomPage(rptName As String) Dim DevString As str_DEVMODE Dim DM As type_DEVMODE Dim strDevModeExtra As String Dim rpt As Report Dim intResponse As Integer ' Opens report in Design view. DoCmd.OpenReport rptName, acDesign Set rpt = Reports(rptName) If Not IsNull(rpt.PrtDevMode) Then strDevModeExtra = rpt.PrtDevMode ' Gets current DEVMODE structure. DevString.RGB = strDevModeExtra LSet DM = DevString If DM.intPaperSize = 256 Then ' Display user-defined size. intResponse = MsgBox("The current custom page size is " _ & DM.intPaperWidth / 254 & " inches wide by " _ & DM.intPaperLength / 254 & " inches long. Do you want " _ & "to change the settings?", 4) Else ' Currently not user-defined. intResponse = MsgBox("The report does not have a custom page " _ & "size. Do you want to define one?", 4) End If If intResponse = 6 Then ' User wants to change settings. ' Initialize fields. DM.lngFields = DM.lngFields Or DM.intPaperSize _ Or DM.intPaperLength Or DM.intPaperWidth DM.intPaperSize = 256 ' Set custom page. ' Prompt for length and width. DM.intPaperLength = InputBox("Please enter page length " _ & "in inches.") * 254 DM.intPaperWidth = InputBox("Please enter page width " _ & "in inches.") * 254 LSet DevString = DM ' Update property. Mid(strDevModeExtra, 1, 94) = DevString.RGB rpt.PrtDevMode = strDevModeExtra End If End IfEnd 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(strName As String) Const DM_PORTRAIT = 1 Const DM_LANDSCAPE = 2 Dim DevString As str_DEVMODE Dim DM As type_DEVMODE Dim strDevModeExtra As String Dim rpt As Report DoCmd.OpenReport strName, acDesign ' Opens report in Design view. Set rpt = Reports(strName) If Not IsNull(rpt.PrtDevMode) Then strDevModeExtra = rpt.PrtDevMode DevString.RGB = strDevModeExtra LSet DM = DevString ' Initialize fields. DM.lngFields = DM.lngFields Or DM.intOrientation If DM.intOrientation = DM_PORTRAIT Then DM.intOrientation = DM_LANDSCAPE Else DM.intOrientation = DM_PORTRAIT End If LSet DevString = DM ' Update property. Mid(strDevModeExtra, 1, 94) = DevString.RGB rpt.PrtDevMode = strDevModeExtra End IfEnd Sub

Page 566: Microsoft Access Language

Microsoft Access Language Reference Página 566 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

PrtDevNames Property

Applies To

Form, Report.

Description

You can use the PrtDevNames property to set or return information about the printer selected in the Print dialog box for a form or report.

Note It is strongly recommended that you consult the Win32 Software Development Kit for complete documentation on the PrtDevMode, PrtDevNames, and PrtMip properties.

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 file name (without an extension) of the device driver. This string is used to specify which printer is initially displayed in the Print 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.

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:".

Page 567: Microsoft Access Language

Microsoft Access Language Reference Página 567 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Microsoft Access sets the PrtDevNames property when you make selections in the Printer section of the Print dialog box. You can also set the property by using Visual Basic.

Remarks

Microsoft Access uses the DEVNAMES structure to initialize the Print dialog box. When the user chooses OK to close the dialog box, information about the selected printer is returned by the PrtDevNames property.

See Also

PrtDevMode property, PrtMip property.

PrtMip Property

Applies To

Form, Report.

Description

You can use the PrtMip property in Visual Basic to set or return the device mode information specified for a form or report in the Print dialog box.

Setting

The PrtMip property setting is a 28-byte structure that maps to settings on the Margins tab for a form or report in the Page Setup dialog box.

The PrtMip property has the following members.

Default Specifies whether the strings specified in the DEVNAMES structure identify the default printer. Before the Print 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.

Member Description

Page 568: Microsoft Access Language

Microsoft Access Language Reference Página 568 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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, grid lines, 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. This member is equivalent to the value of the Number Of Columns box under Grid Settings on the Columns tab of the Page Setup dialog box.

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. This member is equivalent to the value of the Width box under Column Size on the Columns tab of the Page Setup dialog box.

ItemSizeHeight An Integer that specifies the height of the detail section twips. This member is equivalent to the value of the Height box under Column Size on the Columns tab of the Page Setup dialog box.

Page 569: Microsoft Access Language

Microsoft Access Language Reference Página 569 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The PrtMip property setting is read/write in Design view and read-only in other views.

See Also

PrtDevMode property, PrtDevNames property.

Example

The following PrtMip property example demonstrates how to set up the report with two horizontal columns.

Type str_PRTMIP strRGB As String * 28End TypeType type_PRTMIP intLeftMargin As Integer intTopMargin As Integer intRightMargin As Integer intBotMargin As Integer intDataOnly As Integer intWidth As Integer intHeight As Integer intDefaultSize As Integer intColumns As Integer intColumnSpacing As Integer intRowSpacing As Integer intItemLayout As Integer intFastPrint As Integer intDatasheet As IntegerEnd Type

Sub PrtMipCols(strName 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 strName, acDesign Set rpt = Reports(strName) PrtMipString.strRGB = rpt.PrtMip LSet PM = PrtMipString PM.intColumns = 2 ' Create two columns. PM.intRowSpacing = 0.25 * 1440 ' Set 0.25 inch between rows. PM.intColumnSpacing = 0.5 * 1440 ' Set 0.5 inch between columns. PM.intItemLayout = PM_HORIZONTALCOLS LSet PrtMipString = PM ' Update property. rpt.PrtMip = PrtMipString.strRGB

ItemLayout An Integer that specifies horizontal (1953) or vertical (1954) layout of columns. This member is equivalent to Across, Then Down or Down, Then Across respectively under Column Layout on the Columns tab of the Page Setup dialog box.

FastPrint Reserved.

Datasheet Reserved.

Page 570: Microsoft Access Language

Microsoft Access Language Reference Página 570 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

End Sub

The next PrtMip property example shows how to set all margins to 1 inch.

Sub SetMarginsToDefault(strName As String) Dim PrtMipString As str_PRTMIP Dim PM As type_PRTMIP Dim rpt As Report DoCmd.OpenReport strName, acDesign Set rpt = Reports(strName) PrtMipString.strRGB = rpt.PrtMip LSet PM = PrtMipString PM.intLeftMargin = 1 * 1440 ' Set margins. PM.intTopMargin = 1 * 1440 PM.intRightMargin = 1 * 1440 PM.intBotMargin = 1 * 1440 LSet PrtMipString = PM ' Update property. rpt.PrtMip = PrtMipString.strRGBEnd Sub

PSet Method

Applies To

Report object.

Description

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 OnPrint or OnFormat event property for a report section, or the OnPage event property for a report.

The PSet method has the following arguments.

Argument Description

object The Report object on which the point is to be drawn.

Step A keyword that indicates the coordinates are relative to the current graphics position given by the settings for the CurrentX and CurrentY properties of the object argument.

Page 571: Microsoft Access Language

Microsoft Access Language Reference Página 571 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 &HFFFFFF (white) as the color argument.

Tip It's faster to draw a line by using the Line method rather than the PSet method.

See Also

CurrentX, CurrentY properties, DrawMode property, DrawStyle property, DrawWidth property, Event properties, Print event, QBColor function, RGB function.

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. 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 ' Set scale to pixels. Me.ScaleMode = 3 ' Calculate midpoint. sngMidPt = Me.ScaleHeight / 2 ' Loop to draw line down horizontal axis pixel by pixel. For intI = 1 To Me.ScaleWidth Me.PSet(intI, sngMidPt) Next intIEnd Sub

x, y Single values indicating the horizontal and vertical coordinates of the point to set.

color A Long value indicating the RGB (red-green-blue) color to set the point to. 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.

Page 572: Microsoft Access Language

Microsoft Access Language Reference Página 572 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Quit Action

Description

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 has the following argument.

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 clicking Exit on the File menu. If you have any unsaved objects when you click this command, the dialog boxes that appear are the same as those displayed when you use 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.

See Also

Close action, Quit method (DoCmd object), Save action, StopAllMacros action, StopMacro action.

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), Save All (to save all objects without prompting by dialog boxes), or Exit (to quit without saving any objects) in the Options box in the Action Arguments section of the Macro window. The default is Save All.

Page 573: Microsoft Access Language

Microsoft Access Language Reference Página 573 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Quit Method (Application Object)

Applies To

Application object.

Description

The Quit method quits Microsoft Access. You can select one of several options for saving a database object before quitting.

Syntax

Application.Quit [option]

The Quit method has the following argument.

Argument Description

option An intrinsic constant that specifies what happens to unsaved objects when you quit Microsoft Access. This argument can be any of the following constants.

Constant Description

acSaveYes (Default) Saves all objects without displaying a dialog box.

Page 574: Microsoft Access Language

Microsoft Access Language Reference Página 574 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The Quit method has the same effect as clicking Exit on the File menu. You can create a custom menu command or a command 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 the option argument set to acSaveYes.

See Also

Quit action, Quit method (DoCmd object).

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 acPromptEnd Sub

Quit Method (DoCmd Object)

Applies To

DoCmd object.

Description

The Quit method of the DoCmd object carries out the Quit action in Visual Basic. For more information on how the action and its argument work, see the action topic.

Syntax

DoCmd.Quit [options]

The Quit method has the following argument.

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.

Page 575: Microsoft Access Language

Microsoft Access Language Reference Página 575 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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's recommended that you use the existing Quit method of the Application object instead.

See Also

Close method, Quit action, Quit method (Application object), Save method.

Example

The following example displays a dialog box or dialog boxes that ask if you want to save any changed objects before you quit Microsoft Access:

DoCmd.Quit acQuitPrompt

Recalc Method

Applies To

Form object.

Description

The Recalc method immediately updates all calculated controls on a form.

Syntax

form.Recalc

Argument Description

options One of the following intrinsic constants:

acQuitPromptacQuitSaveAll (default)acQuitSaveNone

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

Page 576: Microsoft Access Language

Microsoft Access Language Reference Página 576 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The Recalc method has the following argument.

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.

See Also

Refresh method, Repaint method, Requery method (Control or Form object).

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() Me.RecalcEnd Sub

RecordLocks Property

Applies To

Action query, Crosstab query, Form, Parameter query, QueryDef object, Report, Select query, SQL-Specific query.

Description

You can use the RecordLocks property to determine 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.

l Forms. Specifies how records in the underlying table or query are locked when data in a multiuser database is updated.

Argument Description

form A Form object representing the form that contains the controls for which you want to recalculate the values.

Page 577: Microsoft Access Language

Microsoft Access Language Reference Página 577 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l Reports. Specifies whether records in the underlying table or query are locked while a report is previewed or printed.

l Queries. Specifies 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

Page 578: Microsoft Access Language

Microsoft Access Language Reference Página 578 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using a form's 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 indicator in its record selector.

Tip 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 then select the desired option under Default Record Locking.

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 the RecordLocks property setting.

RecordSelectors Property

Applies To

Form.

Description

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.

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

Page 579: Microsoft Access Language

Microsoft Access Language Reference Página 579 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by 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. You can also use this property for forms whose DefaultView property is set to Single Form.

The record selector displays the unsaved record indicator 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" — only one person can edit a record at a time), there is no visual clue that the record is locked.

See Also

Modal property, NavigationButtons property, PopUp property, ScrollBars property.

RecordsetClone Property

Applies To

Form.

Description

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 by using the same query. If you then apply a filter to the form, the Recordset object reflects the filtering.

This property is available only by using Visual Basic and is read-only in all views.

Remarks

Setting Description Visual Basic

Yes (Default) Each record has a record selector. True (–1)

No No record has a record selector. False (0)

Page 580: Microsoft Access Language

Microsoft Access Language Reference Página 580 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

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 other 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 DAO Bookmark property to the form's Bookmark property.

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.MoveLastMsgBox "My form contains " _ & Forms!Orders.RecordsetClone.RecordCount _ & " records.", vbInformation, "Record Count"

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.

See Also

Bookmark property, Bookmark property ("DAO Language Reference"), FindFirst, FindLast, FindNext, FindPrevious methods ("DAO Language Reference"), MoveFirst, MoveLast, MoveNext, MovePrevious methods ("DAO Language Reference"), Recordset object ("DAO Language Reference"), RecordSource property.

Example

The following example uses the RecordsetClone property to create a new clone of the Recordset object from the Orders form and then prints the names of the fields in the Debug window.

Sub Print_Field_Names() Dim rst As Recordset, intI As Integer Dim fld As Field

Set rst = Me.RecordsetClone For Each fld in rst.Fields ' Print field names. Debug.Print fld.Name NextEnd 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 DAO Bookmark property is assigned to the form's Bookmark property, causing the form to display the found record.

Sub SupplierID_AfterUpdate() Dim rst As Recordset Dim strSearchName As String

Set rst = Me.RecordsetClone strSearchName = Str(Me!SupplierID) rst.FindFirst "SupplierID = " & strSearchName If rst.NoMatch Then

Page 581: Microsoft Access Language

Microsoft Access Language Reference Página 581 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

MsgBox "Record not found" Else Me.Bookmark = rst.Bookmark End If rst.CloseEnd Sub

RecordsetType Property

Applies To

Crosstab query, Form, Select query.

Description

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.

Setting

The RecordsetType property uses the following settings.

You can set this property by using a form's property sheet, a macro, or Visual Basic.

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.

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

Page 582: Microsoft Access Language

Microsoft Access Language Reference Página 582 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

AllowAdditions property, AllowDeletions property, AllowEdits property, Enabled, Locked properties.

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 public variable gstrUserID value is not ADMIN.

Sub Form_Open(Cancel As Integer) Const conSnapshot = 2 If gstrUserID <> "ADMIN" Then Forms!Employees.RecordsetType = conSnapshot End IfEnd Sub

RecordSource Property

Applies To

Form, Report.

Description

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. For example, you can bind a control to the LastName field in the Employees table by setting the control's ControlSource property to LastName.

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.

Page 583: Microsoft Access Language

Microsoft Access Language Reference Página 583 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the RecordSource property by using the form's 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 an SQL statement that returns a single record and change the form's record source depending on criteria selected by the user.

See Also

ControlSource property, RowSourceType, RowSource properties.

Example

The following example sets a form's RecordSource property to the Customers table:

Forms!frmCustomers.RecordSource = "Customers"

Sample setting Description

Employees A table name specifying the Employees table as the source of data.

SELECT Orders!OrderDate FROM Orders;

An SQL statement specifying the OrderDate field on the Orders table as the source of data. 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.

Page 584: Microsoft Access Language

Microsoft Access Language Reference Página 584 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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. The CustomerID has a Text data type.

Sub cmboCompanyName_AfterUpdate() Dim strNewRecord As String strNewRecord = "SELECT * FROM Customers " _ & " WHERE CustomerID = '" _ & Me!cmboCompanyName.Value & "'" Me.RecordSource = strNewRecordEnd Sub

Reference Object

Description

The Reference object refers to a reference set to another application's or project's type library.

Remarks

When you create a Reference object, you set a reference dynamically from Visual Basic.

The Reference object is a member of the References collection. To refer to a particular Reference object in the References collection, use any of the following syntax forms.

The following example refers to the Reference object that represents the reference to the Microsoft Access type library:

Dim ref As ReferenceSet ref = References!Access

Syntax Description

References!referencename

The referencename argument is the name of the Reference object.

References("referencename")

The referencename argument is the name of the Reference object.

References(index) The index argument is the object's numerical position within the collection.

Page 585: Microsoft Access Language

Microsoft Access Language Reference Página 585 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Properties

BuiltIn property, Collection property, FullPath property, GUID property, IsBroken property, Kind property, Major property, Minor property, Name property.

See Also

References collection.

Example

The following example creates a reference to a specified type library:

Function ReferenceFromFile(strFileName As String) As Boolean Dim ref As Reference

On Error GoTo Error_ReferenceFromFile Set ref = References.AddFromFile(strFileName) ReferenceFromFile = True

Exit_ReferenceFromFile: Exit Function

Error_ReferenceFromFile: MsgBox Err & ": " & Err.Description ReferenceFromFile = False Resume Exit_ReferenceFromFileEnd Function

You could call this function by using a procedure such as the following, which creates a reference to the calendar control:

Sub CreateCalendarReference() If ReferenceFromFile("C:\Windows\System\Mscal.ocx") = True Then MsgBox "Reference set successfully." Else MsgBox "Reference not set successfully." End IfEnd Sub

References Collection

Description

The References collection contains Reference objects representing each reference that's currently set.

Remarks

The Reference objects in the References collection correspond to the list of references in the References dialog box, available by clicking References on the Tools menu. Each Reference object represents one selected reference in the list. References that appear in the References dialog box but haven't been selected aren't in the References collection.

You can enumerate through the References collection by using the For Each...Next statement.

Page 586: Microsoft Access Language

Microsoft Access Language Reference Página 586 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The References collection belongs to the Microsoft Access Application object.

Individual Reference objects in the References collection are indexed beginning with 1.

Properties

Count property, Parent property.

Methods

AddFromFile method (References collection), AddFromGUID method, Item method, Remove method (References collection).

Events

ItemAdded event, ItemRemoved event

See Also

Reference object.

Example

See the Reference object example.

Refresh Method

Applies To

Form object.

Description

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 has the following argument.

Page 587: Microsoft Access Language

Microsoft Access Language Reference Página 587 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

Using the Refresh 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 won't 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.

Notes

l 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.

l Don't confuse the Refresh method with the Repaint method, which repaints the screen with any pending visual changes.

See Also

Event properties, GetOption, SetOption methods, Recalc method, Refresh method ("DAO Language Reference"), Requery method (Control or Form object).

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() Me.RefreshEnd Sub

RefreshDatabaseWindow Method

Argument Description

form A Form object that represents the form to refresh.

Page 588: Microsoft Access Language

Microsoft Access Language Reference Página 588 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Application object.

Description

The RefreshDatabaseWindow method updates the Database window after a table, query, form, report, macro, or module has been created, deleted, or renamed.

Syntax

[application.]RefreshDatabaseWindow

The RefreshDatabaseWindow method has the following argument.

Remarks

You can use the RefreshDatabaseWindow method to immediately reflect changes to objects in Microsoft Access in the Database window. For example, if you add a new form from Visual Basic and save it, you can use the RefreshDatabaseWindow method to display the name of the new form on the Forms tab of the Database window immediately after it has been saved.

See Also

RefreshTitleBar method.

Example

The following example creates a new form, saves it, and refreshes the Database window:

Sub CreateFormAndRefresh() Dim frm As Form

Set frm = CreateForm DoCmd.Save , "NewForm" RefreshDatabaseWindowEnd Sub

RefreshTitleBar Method

Applies To

Argument Description

application The Microsoft Access Application object.

Page 589: Microsoft Access Language

Microsoft Access Language Reference Página 589 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Application object.

Description

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.

Syntax

application.RefreshTitleBar

The RefreshTitleBar method uses the following argument.

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 that is 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.

See Also

AppIcon property, AppTitle property.

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 object variable pointing to ' the current database. Set dbs = CurrentDb ' Change title bar. dbs.Properties!AppTitle = "Contacts Database" ' Update title bar on screen. Application.RefreshTitleBar Exit Sub

Argument Description

application The Application object.

Page 590: Microsoft Access Language

Microsoft Access Language Reference Página 590 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 NextEnd Sub

Remove Method (Pages Collection)

Applies To

Pages collection.

Description

The Remove method removes a Page object from the Pages collection of a tab control.

Syntax

object.Remove [item]

The Remove method has the following arguments.

Remarks

The Pages collection is indexed beginning with zero. The leftmost page in the tab control has an index of 0, the page immediately to the right of the leftmost page has an index of 1, and so on.

You can remove a Page object from the Pages collection of a tab control only when the form is in Design view.

See Also

Argument Description

object A string expression that evaluates to the Pages collection of a tab control.

item An integer that specifies the index of the Page object to be removed. The index of the Page object corresponds to the value of the PageIndex property for that Page object. If you omit this argument, the last Page object in the collection is removed.

Page 591: Microsoft Access Language

Microsoft Access Language Reference Página 591 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Add method (Pages collection).

Example

See the Add method (Pages collection) example.

Remove Method (References Collection)

Applies To

References collection.

Description

The Remove method removes a Reference object from the References collection.

Syntax

object.Remove reference

The Remove method has the following arguments.

Remarks

To determine the name of the Reference object you wish to remove, check the Project/Library box in the Object Browser. The names of all references that are currently set appear there. These names correspond to the value of the Name property of a Reference object.

See Also

Name property.

Example

The first of the following two functions adds a reference to the calendar control to the References collection. The second function removes the reference to the calendar control.

Argument Description

object A string expression that evaluates to the References collection.

reference The Reference object that represents the reference you wish to remove.

Page 592: Microsoft Access Language

Microsoft Access Language Reference Página 592 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Function AddReference() As Boolean Dim ref As Reference, strFile As String

On Error GoTo Error_AddReference strFile = "C:\Windows\System\Mscal.ocx" ' Create reference to calendar control. Set ref = References.AddFromFile(strFile) AddReference = True

Exit_AddReference: Exit Function

Error_AddReference: MsgBox Err & ": " & Err.Description AddReference = False Resume Exit_AddReferenceEnd Function

Function RemoveReference() As Boolean Dim ref As Reference

On Error GoTo Error_RemoveReference Set ref = References!MSACAL ' Remove calendar control reference. References.Remove ref RemoveReference = True

Exit_RemoveReference: Exit Function

Error_RemoveReference: MsgBox Err & ": " & Err.Description RemoveReference = False Resume Exit_RemoveReferenceEnd Function

Rename Action

Description

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

Setting

The Rename action has the following arguments.

Action argument

Description

New Name A new name for the database object. Enter the object name in the New Name box in the Action Arguments section of the Macro window. This is a required argument.

Page 593: Microsoft Access Language

Microsoft Access Language Reference Página 593 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

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

You can't 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 rename an object by clicking it in 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.

See Also

CopyObject action, Rename method, Save action, SelectObject action.

Rename Method

Applies To

Object Type The type of object you want to rename. Click Table, Query, Form, Report, Macro, or Module. 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 the Object Type argument 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.

Page 594: Microsoft Access Language

Microsoft Access Language Reference Página 594 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DoCmd object.

Description

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 has the following arguments.

Remarks

If you leave the objecttype and oldname arguments blank (the default constant, acDefault, is assumed for objecttype), 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

Argument Description

newname A string expression that's 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:

acDefault (default)acFormacMacroacModuleacQueryacReportacTable

oldname A string expression that's 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.

Page 595: Microsoft Access Language

Microsoft Access Language Reference Página 595 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

CopyObject method, DoCmd object, Rename action, Save method, SelectObject method.

Example

The following example renames the Employees table with the specified name:

DoCmd.Rename "Old Employees Table", acTable, "Employees"

Repaint Method

Applies To

Form object.

Description

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 has the following argument.

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:

l 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.

Argument Description

form A Form object that represents the form to repaint.

Page 596: Microsoft Access Language

Microsoft Access Language Reference Página 596 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l 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.

Notes

l 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.

l The Repaint method differs from the Echo method in that the Repaint method forces a single immediate repaint, while the Echo method turns repainting on or off.

See Also

Recalc method, RepaintObject action, RepaintObject method.

Example

The following example uses the Repaint method to repaint a form when the form receives the focus:

Private Sub Form_Activate() Me.RepaintEnd Sub

RepaintObject Action

Description

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 has the following arguments.

Action argument

Description

Page 597: Microsoft Access Language

Microsoft Access Language Reference Página 597 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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:

l 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.

l 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.

Notes

l 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.

l 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.

See Also

RepaintObject method, Requery action, SetValue action, ShowAllRecords action.

RepaintObject Method

Applies To

Object Type The type of object to repaint. Click Table, Query, Form, Report, Macro, or Module in 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.

Page 598: Microsoft Access Language

Microsoft Access Language Reference Página 598 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DoCmd object.

Description

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 has the following arguments.

Remarks

Using the RepaintObject method with no arguments (the default constant, acDefault, is assumed for the objecttype argument) 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 95. If you want to repaint a form, it's recommended that you use the existing Repaint method of the Form object instead.

See Also

DoCmd object, Recalc method, Refresh method, Repaint method, RepaintObject action, Requery method (Control or Form object), Requery method (DoCmd object), ShowAllRecords method.

Example

Argument Description

objecttype One of the following intrinsic constants:

acDefault (default)acFormacMacroacModuleacQueryacReportacTable

objectname A string expression that's the valid name of an object of the type selected by the objecttype argument.

Page 599: Microsoft Access Language

Microsoft Access Language Reference Página 599 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The following example repaints the table Customers:

DoCmd.RepaintObject acTable, "Customers"

RepeatSection Property

Applies To

Report.

Description

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.

Note The RepeatSection property only applies to group headers on a report.

Setting

The RepeatSection property uses the following settings.

You can set the RepeatSection property by using the group header section's property sheet, a macro, or 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.

ReplaceLine Method

Applies To

Module object.

Setting Description Visual Basic

Yes The group header is repeated. True (–1)

No (Default) The group header isn't repeated.

False (0)

Page 600: Microsoft Access Language

Microsoft Access Language Reference Página 600 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

The ReplaceLine method replaces a specified line in a standard module or a class module.

Syntax

object.ReplaceLine line, string

The ReplaceLine method has the following arguments.

Remarks

Lines in a module are numbered beginning with one. To determine the number of lines in a module, use the CountOfLines property.

See Also

CountOfLines property, DeleteLines method, Find method.

Example

See the Find method example.

ReplicationConflictFunction Property

Applies To

Document object.

Description

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

Argument Description

object A Module object.

line A Long value that specifies the number of the line to be replaced.

string The text that is to replace the existing line.

Page 601: Microsoft Access Language

Microsoft Access Language Reference Página 601 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

property, Microsoft Access calls your conflict resolution function, rather than the built-in Conflict Resolver, when the user requests to resolve conflicts.

Settings

Set the ReplicationConflictFunction property to a text string that's the name of the Function procedure you wish to call. Note that the setting must be the name of a Function procedure; it can't be the name of a Sub procedure. Unless this property has been set, Microsoft Access calls the 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. For more information, see the CreateProperty method.

When you create and append the ReplicationConflictFunction property, you must also provide a value of True (–1) for the optional DDL argument of the CreateProperty method. This argument ensures that users can't change or delete the new Property object unless they have dbSecWriteDef permissions. If you don't supply a value of True for this argument, your custom conflict resolution code won't be called.

To return control to the built-in Conflict Resolver again, remove this property from the Properties collection.

You can also add or delete this property on the Custom tab of the DatabaseName 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 the built-in Conflict Resolver. The wizard presents each conflict to the user, who must manually determine which changed record contains the correct data.

If you prefer to automate conflict resolution for your application, you can write custom procedures to resolve conflicts, and then 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.

If you write your own custom conflict resolution code, it must also handle replication design errors and replication data errors. To see an example, open the wizard database Wzcnf80.mda in the Office folder and examine the source code.

See Also

CreateProperty method ("DAO Language Reference"), Property object ("DAO Language Reference").

Example

The following function sets a Microsoft Access property on a DAO object. You can use this function to set the ReplicationConflictFunction property. If the property doesn't already exist in the Properties collection of the UserDefined Document object, Microsoft Access creates and

Page 602: Microsoft Access Language

Microsoft Access Language Reference Página 602 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

appends it. Note that in order to set this property, you must provide a value of True (–1) for the optional blnDDL argument.

Function SetAccessProperty(obj As Object, strName As String, _ intType As Integer, varSetting As Variant, _ Optional blnDDL As Boolean) As Boolean Dim prp As Property Const intPropNotFound As Integer = 3270

On Error GoTo Error_SetAccessProperty ' Explicitly refer to Properties collection. obj.Properties(strName) = varSetting obj.Properties.Refresh SetAccessProperty = TrueExit_SetAccessProperty: Exit Function

Error_SetAccessProperty: If Err = intPropNotFound Then ' Check whether optional argument has been passed. If Not IsMissing(blnDDL) Then ' Create property, denote type, set initial value, indicate DDL. Set prp = obj.CreateProperty(strName, intType, varSetting, blnDDL) Else ' Create property, denote type, set initial value. Set prp = obj.CreateProperty(strName, intType, varSetting) End If ' Append Property object to Properties collection. obj.Properties.Append prp obj.Properties.Refresh SetAccessProperty = True Resume Exit_SetAccessProperty Else MsgBox Err & ": " & vbCrLf & Err.Description SetAccessProperty = False Resume Exit_SetAccessProperty End IfEnd Function

The following procedure calls the SetAccessProperty function to set the ReplicationConflictFunction property:

Sub SetConflictResolver() Dim dbs As Database, ctr As Container, doc As Document Dim blnReturn As Boolean

' Return reference to current database. Set dbs = CurrentDb ' Return reference to Databases container. Set ctr = dbs.Containers!Databases ' Return reference to SummaryInfo Document object. Set doc = ctr.Documents!userdefined blnReturn = SetAccessProperty(doc, _ "ReplicationConflictFunction", dbText, "CustomResolver", True) ' Evaluate return value. If blnReturn = True Then Debug.Print "Property set successfully." Else Debug.Print "Property not set successfully." End IfEnd Sub

Report Object

Description

Page 603: Microsoft Access Language

Microsoft Access Language Reference Página 603 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

A Report object refers to a particular Microsoft Access report.

Remarks

A Report object is a member of the Reports collection, which is a collection of all currently open reports. Within the Reports collection, individual reports are indexed 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 ([ ]).

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 control named NewData on a report called OrderReport.

' Implicit reference.Reports!OrderReport!NewData

' Explicit reference.Reports!OrderReport.Controls!NewData

Properties

ActiveControl property, Application property, Caption property, Count property, CurrentRecord property, CurrentX, CurrentY properties, DateGrouping property, Dirty property, DrawMode property, DrawStyle property, DrawWidth property, Event properties, FastLaserPrinting property, FillColor property, FillStyle property, Filter property, FilterOn property, FontBold property, FontItalic, FontUnderline properties, FontName, FontSize properties, ForeColor property, Form, Report properties, FormatCount property, GridX, GridY properties, GroupLevel property, GrpKeepTogether property, HasData property, HasModule property, Height, Width properties, HelpContextID, HelpFile properties, hWnd property, LayoutForPrint property, Left, Top properties, MenuBar property, MinMaxButtons property, Module property, MoveLayout, NextRecord, PrintSection properties, Name property, OrderBy property, OrderByOn property, Page, Pages properties, PageHeader, PageFooter properties, Painting property, PaintPalette

Syntax Example

Reports!reportname Reports!OrderReport

Reports![report name]

Reports![Order Report]

Reports("reportname")

Reports("OrderReport")

Reports(index) Reports(0)

Page 604: Microsoft Access Language

Microsoft Access Language Reference Página 604 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

property, PaletteSource property, Parent property, Picture property, PictureAlignment property, PictureData property, PicturePages property, PictureSizeMode property, PictureTiling property, PictureType property, PrintCount property, PrtDevMode property, PrtDevNames property, PrtMip property, RecordLocks property, RecordSource property, ScaleHeight, ScaleWidth properties, ScaleLeft, ScaleTop properties, ScaleMode property, Section property, ShortcutMenuBar property, Tag property, Toolbar property, Visible property.

Methods

Circle method, DefaultControl method, Line method, Print method, PSet method, Scale method, TextHeight method, TextWidth method.

Events

Activate, Deactivate events, Error event, NoData event, Open, Close events, Page event.

See Also

Controls collection, 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. With rpt .RecordSource = "Products" .Caption = "Products Report" End With ' Restore new report. DoCmd.RestoreEnd 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 rptEnd Sub

Report Property

Page 605: Microsoft Access Language

Microsoft Access Language Reference Página 605 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Form, Report Properties.

Reports Collection

Description

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 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. If you opened Report1 and then opened Report2, Report2 would be referenced in the Reports collection by its index as Reports(1). If you then closed Report1, Report2 would be referenced in the Reports collection by its index as Reports(0).

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.

You can't add or delete a Report object from the Reports collection.

Properties

Application property, Count property, Item property (collections), Item property (ObjectFrame control), Parent property.

See Also

Application object, Container object ("DAO Language Reference"), Document object ("DAO Language Reference"), Documents collection ("DAO Language Reference"), For Each...Next statement, Report object.

Example

See the Report object example.

Page 606: Microsoft Access Language

Microsoft Access Language Reference Página 606 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Requery Action

Description

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 has the following argument.

Remarks

The Requery action does one of the following:

l Reruns the query on which the control or object is based.l 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:

l List boxes and combo boxes.l Subform controls.l OLE objects, such as charts.l Controls containing domain aggregate functions, such as DSum.

If the specified control isn't based on a query or table, this action forces a recalculation of the control.

Action argument

Description

Control Name The name of the control you want to update. Enter the control name in the Control Name box in the Action Arguments section of the Macro window. 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.

Page 607: Microsoft Access Language

Microsoft Access Language Reference Página 607 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 doesn't do.

If you want to requery a control that isn't 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 DAO Requery method works the same way as the Microsoft Access Requery method.

See Also

RepaintObject action, Requery method (Control or Form object), Requery method ("DAO Language Reference"), Requery method (DoCmd object), ShowAllRecords action.

Requery Method (Control or Form Object)

Applies To

Combo Box control, Control object, Form object, List Box control, Page.

Description

The Requery method updates the data underlying a specified form, or a control that's on the active form, by requerying the source of data for the form or control.

Syntax

[object.]Requery

The Requery method has 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.

Page 608: Microsoft Access Language

Microsoft Access Language Reference Página 608 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can use this method to ensure that a form or control displays the most recent data.

The Requery method does one of the following:

l Reruns the query on which the form or control is based.l Displays any new or changed records or removes deleted records from the table on which

the form or control is based.l Updates records displayed based on any changes to the Filter property of the form.

Controls based on a query or table include:

l List boxes and combo boxes.l Subform controls.l OLE objects, such as charts.l Controls for which the ControlSource property setting includes domain aggregate functions

or SQL aggregate function.

If you specify any other type of control for the object argument, the record source for the form is requeried.

If the control specified by the object argument isn't bound to a field in a table or query, the Requery method forces a recalculation of the control.

If you omit the object argument, 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.

Notes

l 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 doesn't reflect new records or deleted records in the record source. The Repaint method simply repaints the specified form and its controls.

l 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.

l 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.

See Also

Recalc method, Refresh method, Repaint method, Requery action, Requery method ("DAO Language Reference"), Requery method (DoCmd object).

Example

Page 609: Microsoft Access Language

Microsoft Access Language Reference Página 609 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The following 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.RequeryEnd Sub

Requery Method (DoCmd Object)

Applies To

DoCmd object.

Description

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 has the following arguments.

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 ctlLstBox As ControlSet ctlLstBox = Forms!Form1!Field3DoCmd.Requery ctlLstBox.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 95. If you want to requery a control that's not on the active object, you must use the Requery method in Visual Basic, not the

Argument Description

controlname A string expression that's the name of a control on the active object.

Page 610: Microsoft Access Language

Microsoft Access Language Reference Página 610 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 The Requery method for Data Access Objects (DAO) works the same way as the Microsoft Access Requery method.

See Also

Requery method (Control or Form object), Requery method ("DAO Language Reference").

Example

The following example uses the Requery method to update the EmployeeList control:

DoCmd.Requery "EmployeeList"

Required Property

Applies To

Table field.

Description

You can use the Required property to specify whether 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 Null values in a field, you must not only set the Required property to No but, if there is a ValidationRule property setting, it must also explicitly state "validationrule Or Is Null".

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)

Page 611: Microsoft Access Language

Microsoft Access Language Reference Página 611 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property for all table fields (except AutoNumber data type fields) by using the table's property sheet or Visual Basic.

Note To access a field's Required property in Visual Basic, use the DAO 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 — 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.

Tip You can 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 ENTERPresses SPACEBAREnters a zero-length string

NullNull(not allowed)

No Yes Presses ENTERPresses SPACEBAREnters a zero-length string

NullNullZero-length string

Page 612: Microsoft Access Language

Microsoft Access Language Reference Página 612 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

If you set the Required property to Yes for a field in a table that already contains data, Microsoft Access gives you the option of checking 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 don't 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.

See Also

AllowZeroLength property, AllowZeroLength property ("DAO Language Reference"), InputMask property, Required property ("DAO Language Reference"), ValidationRule, ValidationText properties.

Resize Event

Applies To

Form.

Description

The Resize event occurs when a form is opened and whenever the size of a form changes.

Remarks

To run a macro or event procedure when this event occurs, set the OnResize property to the name of the macro or to [Event Procedure].

Yes No Presses ENTERPresses SPACEBAREnters a zero-length string

(not allowed)(not allowed)(not allowed)

Yes Yes Presses ENTERPresses SPACEBAREnters a zero-length string

(not allowed)Zero-length stringZero-length string

Page 613: Microsoft Access Language

Microsoft Access Language Reference Página 613 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 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

Note You need to be careful if you use a MoveSize, Maximize, Minimize, or Restore action (or the corresponding methods of the DoCmd object) in a Resize macro or event procedure. These actions can trigger a Resize event for the form, and thus cause a cascading event.

See Also

Activate, Deactivate events, Current event, Event properties, GotFocus, LostFocus events, Load, Unload events, MoveSize action, Open, Close events, OpenForm action, Repaint method, RepaintObject action, SetFocus method.

Resize Event — Event Procedures

Description

To create an event procedure that runs 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.

See Also

Resize event — macros.

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.

Page 614: Microsoft Access Language

Microsoft Access Language Reference Página 614 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To try the example, add the following event procedures to a form named Contacts that contains a command button named Maximize:

Private Sub Maximize_Click() DoCmd.MaximizeEnd Sub

Private Sub Form_Resize() Forms!Contacts.RepaintEnd Sub

Resize Event — Macros

Description

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.

See Also

Resize event — event procedures.

Restore Action

Description

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

Setting

The Restore action doesn't have any arguments.

Remarks

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

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

The Restore action has the same effect as clicking the Restore button in the window's upper-

Page 615: Microsoft Access Language

Microsoft Access Language Reference Página 615 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Maximize action, Minimize action, MoveSize action, Restore method, SelectObject action.

Restore Method

Applies To

DoCmd object.

Description

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 has no arguments.

See Also

DoCmd object, Maximize method, Minimize method, MoveSize method, Restore action, SelectObject method.

Retreat Event

Applies To

Report section.

Description

The Retreat event occurs when Microsoft Access returns to a previous report section during report formatting.

Note The Retreat event applies to all report sections except page headers and footers.

Remarks

To run a macro or event procedure when this event occurs, set the OnRetreat property to the name of the macro or to [Event Procedure].

Page 616: Microsoft Access Language

Microsoft Access Language Reference Página 616 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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:

l Groups (except for page headers and footers) for which the KeepTogether property is set to either Whole Group or With First Detail.

l Subreports or subforms for which the CanGrow and/or CanShrink property is set to Yes.l 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 actually print 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 want to perform only 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).

See Also

Event properties, Format event, FormatCount property, NoData event, Page event, Print event, PrintCount property.

Retreat Event — Event Procedures

Description

To create an event procedure that runs 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 has the following argument.

Page 617: Microsoft Access Language

Microsoft Access Language Reference Página 617 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can't cancel the Retreat event.

See Also

Retreat event — macros.

Retreat Event — Macros

Description

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.

See Also

Retreat event — event procedures.

ReturnsRecords Property

Applies To

SQL-Specific query.

Description

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 ReturnsRecords property to Yes to display all employee records in the query's datasheet.

Note The ReturnsRecords property applies only to pass-through queries.

Argument Description

sectionname The name of the report section whose Retreat event procedure you want to run.

Page 618: Microsoft Access Language

Microsoft Access Language Reference Página 618 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The ReturnsRecords property uses the following settings.

You can set this property by using the query's property sheet or Visual Basic.

Tip You can access a pass-through query's ReturnsRecords property in Visual Basic, but the preferred method is to use the DAO 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 as an action query does.

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.

See Also

LogMessages property, ODBCTimeout property, ODBCTimeout property ("DAO Language Reference"), ReturnsRecords property ("DAO Language Reference"), UniqueRecords property, UniqueValues property.

RowHeight Property

Applies To

Form, QueryDef object, Table, TableDef object.

Description

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 Description Visual Basic

Yes (Default) The query returns records (as a select query does).

True ( )

No The query doesn't return records (as an action query does).

False (0)

Page 619: Microsoft Access Language

Microsoft Access Language Reference Página 619 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

You can set the RowHeight property in Datasheet view by dragging the lower border of the record selector or by clicking Row Height on the Format menu. When you set the RowHeight property by using the Row Height command, the value is expressed in points.

In Visual Basic, the RowHeight property setting is a Long Integer 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 ( ).

See Also

ColumnHidden property, ColumnOrder property, ColumnWidth property.

Example

See the ColumnWidth property example.

RowSourceType Property (User-Defined Function) — Code Argument Values

Description

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 Function procedure has the following five required arguments.

Argument Description

fld A control variable that refers to the list box or combo box being filled.

Page 620: Microsoft Access Language

Microsoft Access Language Reference Página 620 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note Because Microsoft Access calls a user-defined 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 by repeatedly using different values in the code argument to specify the information it needs. The code argument can use the following intrinsic constants.

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 An intrinsic constant that specifies the kind of information being requested.

Constant Meaning Function returns

acLBInitialize Initialize Nonzero if the function can fill the list; False (0) or Null otherwise.

acLBOpen Open Nonzero ID value if the function can fill the list; False or Null otherwise.

acLBGetRowCount Number of rows

Number of rows in the list (can be zero); –1 if unknown.

acLBGetColumnCount Number of columns

Number of columns in the list (can't be zero); must match the property sheet value.

Page 621: Microsoft Access Language

Microsoft Access Language Reference Página 621 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Microsoft Access calls your user-defined function once for acLBInitialize, acLBOpen, acLBGetRowCount, and acLBGetColumnCount. It initializes the user-defined function, opens the query, and determines the number of rows and columns.

Microsoft Access calls your user-defined function twice for acLBGetColumnWidth — 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 user-defined function is called for acLBGetValue and acLBGetFormat 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 user-defined function for acLBEnd 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 user-defined function with that code.

Tip You can use the Select Case code structure from the example as a template for your own

acLBGetColumnWidth Column width Width (in twips) of the column specified by the col argument; –1 to use the default width.

acLBGetValue List entry List entry to be displayed in the row and column specified by the row and col arguments.

acLBGetFormat 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; –1 to use the default format.

acLBEnd End (the last call to a user-defined function always uses this value)

Nothing.

acLBClose (Not used) Not used.

Page 622: Microsoft Access Language

Microsoft Access Language Reference Página 622 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

RowSourceType property user-defined functions.

See Also

Static statement.

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 acLBInitialize ' Initialize. ListMondays = True Case acLBOpen ' Open. ListMondays = Timer ' Unique ID. Case acLBGetRowCount ' Get rows. ListMondays = 4 Case acLBGetColumnCount ' Get columns. ListMondays = 1 Case acLBGetColumnWidth ' Get column width. ListMondays = -1 ' Use default width. Case acLBGetValue ' Get the data. intOffset = Abs((9 - Weekday(Now))Mod 7) ListMondays = Format(Now() + intOffset + 7 * row,"mmmm d") End SelectEnd Function

The next 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) As String, Entries As Integer Dim ReturnVal As Variant ReturnVal = Null Select Case code Case acLBInitialize ' Initialize. Entries = 0 dbs(Entries ) = Dir("*.MDB") Do Until dbs(Entries) = "" Or Entries >= 127 Entries = Entries+1 dbs(Entries) = Dir Loop ReturnVal = Entries Case acLBOpen ' Open. ReturnVal = Timer ' Generate unique ID for control. Case acLBGetRowCount ' Get number of rows. ReturnVal = Entries Case acLBGetColumnCount ' Get number of columns. ReturnVal = 1 Case acLBGetColumnWidth ' Column width. ReturnVal = -1 ' -1 forces use of default width. Case acLBGetValue ' Get data. ReturnVal = dbs(row) Case acLBEnd ' End. Erase dbs End Select ListMDBs = ReturnValEnd Function

Page 623: Microsoft Access Language

Microsoft Access Language Reference Página 623 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

RowSourceType, RowSource Properties

Applies To

Chart control, Combo Box control, List Box control, Table field, Unbound Object Frame control.

Description

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 uses the following settings.

Note You can also set the RowSourceType property with a user-defined function. 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.

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.

For this RowSourceType setting

Enter this RowSource setting

Page 624: Microsoft Access Language

Microsoft Access Language Reference Página 624 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note If the RowSourceType property is set to a user-defined function, the RowSource property can be left blank.

You can set the RowSourceType and RowSource properties by using the control's property sheet, a macro, or Visual Basic.

For table fields, you can set these properties on the Lookup tab in the Field Properties section of 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 by 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 don't 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.

See Also

BoundColumn property, ColumnWidths property, ControlSource property, RecordSource property, RowSourceType property (user-defined function) — code argument values.

Example

The following examples show sample RowSource property settings for each RowSourceType property setting.

When the RowSourceType Property Is Set to Value List

If the RowSourceType property is set to Value List, the following table shows valid settings for

Table/Query A table name, query name, or SQL statement.

Value List A list of items with semicolons (;) as separators.

Field List A table name, query name, or SQL statement.

Page 625: Microsoft Access Language

Microsoft Access Language Reference Página 625 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

the RowSource and ColumnCount properties and an illustration of the resulting list.

When the RowSourceType Property 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 — 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 the RowSourceType Property Is Set to Field List

If the RowSourceType property is set to Field List and the RowSource property to CategoryList (the query described in the previous example), the resulting list looks like the following illustration.

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

Page 626: Microsoft Access Language

Microsoft Access Language Reference Página 626 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

When the RowSourceType Property Is Set to a User-Defined Function

If the RowSourceType property is set to the name of a user-defined function, then the RowSource property setting can 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 as in the following illustration.

Example

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!Employees!cmboNames.RowSourceType = "Table/Query"Forms!Employees!cmboNames.RowSource = "EmployeeList"

Run Method

Applies To

Application object.

Description

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 Automation, formerly called OLE Automation. For example, you can use the Run method from an ActiveX component to carry out a Sub procedure that is defined within a Microsoft Access database.

Syntax

application.Run procedure[, arg1, arg2, ..., arg30]

The Run method has the following arguments.

Page 627: Microsoft Access Language

Microsoft Access Language Reference Página 627 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can set a reference to the Microsoft Access type library from any other ActiveX component 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 named NewForm in a database with its ProjectName property set to "WizCode." The NewForm procedure takes a string argument. You can call NewForm in the following manner from Visual Basic:

Dim appAccess As New Access.ApplicationappAccess.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 the procedure argument, as shown in the preceding example, 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.

Microsoft Access ignores any value returned by a procedure called by the Run method.

Argument Description

application The Application object.

procedure The name of the Function or Sub procedure to be run. If you are calling a procedure in another database use the project name and the procedure name separated by a dot in the form:

"projectname.procedurename"

If you execute Visual Basic code containing the Run method in a library database, Microsoft Access looks for the procedure first in the library database, then in the current database.

arg1, arg2, ...

Optional. The arguments for the specified Function or Sub procedure. You can supply a maximum of thirty arguments.

Page 628: Microsoft Access Language

Microsoft Access Language Reference Página 628 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

CreateObject function, GetObject function, Set statement.

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 Active X component.

To try this example, create a new database called WizCode.mdb and set its ProjectName property to WizCode. Open a new module in that database and 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 8.0 Object Library in the References dialog box.

' Include in Declarations section of module.Dim appAccess As Access.Application

Sub RunAccessSub() ' Create instance of Access Application object. Set appAccess = _ CreateObject("Access.Application.8") ' Open WizCode database in Microsoft Access window. appAccess.OpenCurrentDatabase "C:\My Documents\WizCode.mdb", False ' Run Sub procedure. appAccess.Run "Greeting", "Joe" Set appAccess = NothingEnd Sub

RunApp Action

Description

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

Setting

The RunApp action has the following argument.

Page 629: Microsoft Access Language

Microsoft Access Language Reference Página 629 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 by using Automation.

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

In Windows 3.1, 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, by 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

Description

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

Setting

The RunCode action has the following argument.

Action argument

Description

Command Line

The command line used to start the application (including the path and any other necessary parameters, such as switches that run the application in a particular mode). Enter the command line in the Command Line box in the Action Arguments section of the Macro window. This is a required argument.

Page 630: Microsoft Access Language

Microsoft Access Language Reference Página 630 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 doesn't 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 clicking 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's or report's class module and then in the standard modules. Microsoft Access doesn't search the class modules that appear on the Modules tab in the Database window for the function specified by the Function Name argument.

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

See Also

Action argument

Description

Function Name

The name of the Visual Basic Function procedure to call. Put any function arguments in parentheses. Enter the function name in the Function Name box in the Action Arguments section of the Macro window. 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 the desired function in the list in the Expression Builder.

Page 631: Microsoft Access Language

Microsoft Access Language Reference Página 631 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Eval function, OpenModule action.

RunCommand Action

Description

You can use the RunCommand action to run a built-in Microsoft Access command. The command may appear on a Microsoft Access menu bar, toolbar, or shortcut menu.

Setting

The RunCommand action has the following action argument.

Remarks

In Microsoft Access 97, the RunCommand action replaces the DoMenuItem action. When you open and save a macro from a previous version of Microsoft Access that contains a DoMenuItem action, the action and its action arguments will automatically be converted to the equivalent RunCommand action. The DoMenuItem action no longer appears in the list of actions in the Macro window in Microsoft Access 97.

You can use the RunCommand action to run a Microsoft Access command from a custom menu bar, global menu bar, custom shortcut menu, or global shortcut menu. However, it's normally easier to use the Customize dialog box, available by pointing to Toolbars on the View menu and clicking Customize, to add Microsoft Access commands to custom menus and shortcut menus. The Commands tab on the Customize dialog box lists the built-in Microsoft Access commands that appear on the Microsoft Access toolbars and menus.

You can use the RunCommand action in a macro with conditional expressions to run a command depending on certain conditions.

Note The Microsoft Access 97 File menu shows the most recently used databases. You can click one of these databases instead of clicking Open Database. These database items don't appear in the drop-down list box for the Command argument, and aren't available by using the RunCommand action in a macro.

When you convert a Microsoft Access database from a previous version of Microsoft Access,

Action argument

Description

Command The name of the command you want to run. The Command box shows the available built-in commands in Microsoft Access, in alphabetical order. This is a required argument.

Page 632: Microsoft Access Language

Microsoft Access Language Reference Página 632 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

some commands may no longer be available. A command may have been renamed, moved to a different menu, or may no longer be available in Microsoft Access 97. The DoMenuItem actions for such commands can't be converted to RunCommand actions. When you open the macro, Microsoft Access will display a RunCommand action with a blank Command argument for such commands. You must edit the macro and enter a valid command argument, or delete the RunCommand action.

To run the RunCommand action in Visual Basic, use the RunCommand method of the Application object. (This is equivalent to the RunCommand method of the DoCmd object.)

See Also

AddMenu action, RunCommand method.

RunCommand Method

Applies To

Application object, DoCmd object.

Description

The RunCommand method runs a built-in menu or toolbar command.

Syntax

[object.]RunCommand command

The RunCommand method has the following arguments.

Remarks

Each menu and toolbar command in Microsoft Access has an associated constant that you can use with the RunCommand method to run that command from Visual Basic.

For a list of possible constants for the command argument, see RunCommand Method Constants.

Argument Description

object Optional. The Application object or the DoCmd object.

command An intrinsic constant that specifies which built-in menu or toolbar command is to be run.

Page 633: Microsoft Access Language

Microsoft Access Language Reference Página 633 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can also view these constants in the Object Browser. Select Access in the Project/Library box, then select AcCommand in the Classes list. The constants appear in the Members Of list.

You can't use the RunCommand method to run a command on a custom menu or toolbar. You can only use it with built-in menus and toolbars.

The RunCommand method replaces the DoMenuItem method of the DoCmd object.

See Also

RunCommand action.

Example

The following example uses the RunCommand method to open the Options dialog box (available by clicking Options on the Tools menu):

Function OpenOptionsDialog() As Boolean On Error GoTo Error_OpenOptionsDialog DoCmd.RunCommand acCmdOptions OpenOptionsDialog = True

Exit_OpenOptionsDialog: Exit Function

Error_OpenOptionsDialog: MsgBox Err & ": " & Err.Description OpenOptionsDialog = False Resume Exit_OpenOptionsDialogEnd Function

RunMacro Action

Description

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

You can use this action:

l To run a macro from within another macro.l To run a macro based on a certain condition.l To attach a macro to a custom menu command.

Setting

The RunMacro action has the following arguments.

Page 634: Microsoft Access Language

Microsoft Access Language Reference Página 634 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 you can use to select and run 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:

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

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's 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.

Page 635: Microsoft Access Language

Microsoft Access Language Reference Página 635 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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

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

l 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 a macro containing the RunMacro action, 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 runs the next action.

Notes

l You can call a macro in the same macro group or in another macro group.l 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.

Tip You can use the RunMacro action in a macro group that defines custom commands for a custom menu bar to run a macro from the custom menu. However, it's easier to use the new command bars functionality to run a macro from a menu bar, toolbar, or shortcut menu. On the View menu, point to Toolbars and click Customize to display the Customize dialog box. On the Toolbars tab, select the menu bar, toolbar, or shortcut menu that you want to run the macro from. On the Commands tab, click All Macros in the Categories box, then in the Commands box select and drag the macro you want to run to the menu bar, toolbar, or shortcut menu. When you click the icon for this macro on the menu bar, toolbar, or shortcut menu, Microsoft Access will run the macro. You can also drag a macro from the Database window on to a menu bar or toolbar and Microsoft Access will create an icon that runs that macro.

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

See Also

AddMenu action, RunMacro method.

RunMacro Method

Applies To

DoCmd object.

Description

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]

Page 636: Microsoft Access Language

Microsoft Access Language Reference Página 636 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The RunMacro method has the following arguments.

Remarks

You can use macrogroupname.macroname syntax 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.

Example

The following example runs the macro Print Sales:

DoCmd.RunMacro "Print Sales"

RunningSum Property

Applies To

Report, Text Box control.

Argument Description

macroname A string expression that's the valid name of a macro in the current database.

If you run 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's evaluated each time the macro runs. When it evaluates to False (0), the macro stops running.

Page 637: Microsoft Access Language

Microsoft Access Language Reference Página 637 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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, you can 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 uses the following settings.

You can set the RunningSum property by 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.

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

Page 638: Microsoft Access Language

Microsoft Access Language Reference Página 638 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can have up to 10 nested group levels in a report.

Example

The following example shows a sales report with two group levels — 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 Food100

YTD Sales100

Type of Food: Meat

03-Jan 90

20-Jan 60

January Meat 150 Jan Food250

YTD Sales250

Month: February

Page 639: Microsoft Access Language

Microsoft Access Language Reference Página 639 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

The following example sets the RunningSum property for a text box named SalesTotal to 2 (Over All):

Reports!rptSales!SalesTotal.RunningSum = 2

RunPermissions Property

Applies To

Action query, Crosstab query, Parameter query, Select query.

Description

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 wouldn't have permission to run. For example, as a user, you may have read-only permission for queries, while the owner of the queries has

Type of Food: Chocolates

05-Feb 70

19-Feb 80

February Chocolates

150 Feb Food150

YTD Sales400

Type of Food: Meat

12-Feb 150

22-Feb 100

February Meat 250 Feb Food400

YTD Sales650

Page 640: Microsoft Access Language

Microsoft Access Language Reference Página 640 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

read/write permission. If the owner sets the RunPermissions property to specify the owner's permissions, you can run an append query to add records to a table.

Setting

The RunPermissions property uses the following settings.

You can set this property by using the query's 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.

See Also

WITH OWNERACCESS OPTION Declaration ("SQL Language Reference").

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. You enter this SQL statement in SQL view of the Query window.

SELECT Categories.CategoryID, Categories.CategoryName, Categories.DescriptionFROM Categories WITH OWNERACCESS OPTION;

RunSQL Action

Description

You can use the RunSQL action to run a Microsoft Access action query by using the corresponding SQL statement. You can also run a data-definition query.

Setting

The RunSQL action has the following arguments.

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.

Page 641: Microsoft Access Language

Microsoft Access Language Reference Página 641 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 by 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.

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.

Use Transaction

Select Yes to include this query in a transaction. Select No if you don't want to use a transaction. The default is Yes. Previous versions of Microsoft Access have always included the query in a transaction when you ran this action. If you select No for this argument, the query may run faster.

Query type SQL statement

Action

Append INSERT INTO

Delete DELETE

Page 642: Microsoft Access Language

Microsoft Access Language Reference Página 642 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 View on the View menu in the Query window. You can 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.

See Also

BeginTrans, CommitTrans, Rollback methods ("DAO Language Reference"), OpenQuery action, RunSQL method, Transactions property ("DAO Language Reference").

RunSQL Method

Applies To

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

Page 643: Microsoft Access Language

Microsoft Access Language Reference Página 643 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

DoCmd object.

Description

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[, usetransaction]

The RunSQL method has the following arguments.

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).

If you leave the usetransaction argument blank, don't use a comma following the sqlstatement argument.

See Also

OpenQuery method, RunSQL action.

Example

The following example updates the Employees table, changing each sales manager's title to Regional Sales Manager:

DoCmd.RunSQL "UPDATE Employees " & _

Argument Description

sqlstatement A string expression that's 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.

usetransaction Use True (–1) to include this query in a transaction. Use False (0) if you don't want to use a transaction. If you leave this argument blank, the default (True) is assumed.

Page 644: Microsoft Access Language

Microsoft Access Language Reference Página 644 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

"SET Employees.Title = 'Regional Sales Manager' " & _ "WHERE Employees.Title = 'Sales Manager';"

Save Action

Description

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 in some cases (this functions the same as the Save As command on the File menu).

Setting

The Save action has the following arguments.

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

Action argument

Description

Object Type The type of object you want to save. Click Table, Query, Form, Report, Macro, or Module in the Object Type box 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 by the Object Type argument. If you leave the Object Type argument blank, you can leave this argument blank to save the active object, or, in some cases, 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.

Page 645: Microsoft Access Language

Microsoft Access Language Reference Página 645 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Note You can't use the Save action to save any of the following with a new name:

l A form in Form view or Datasheet view.l A report in Print Preview.l A module.

The Save action, whether it's 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.

See Also

Close action, CopyObject action, Quit action, Rename action, Save method, TransferDatabase action.

Save Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Page 646: Microsoft Access Language

Microsoft Access Language Reference Página 646 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If you leave the objecttype and objectname arguments blank (the default constant, acDefault, is assumed for the objecttype argument), 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.

Note You can't use the Save method to save any of the following with a new name:

l A form in Form view or Datasheet view.l A report in Print Preview.l A module.

The Save method, whether it's 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.

See Also

Close method, CopyObject method, Quit method (Application object), Quit method (DoCmd object), Rename method, Save action, TransferDatabase method.

Example

The following example uses the Save method to save the form named "New Employees Form". This form must be open when the code containing this method runs.

DoCmd.Save acForm, "New Employees Form"

Argument Description

objecttype One of the following intrinsic constants:

acDefault (default)acFormacMacroacModuleacQueryacReportacTable

objectname A string expression that's the valid name of an object of the type selected by the objecttype argument.

Page 647: Microsoft Access Language

Microsoft Access Language Reference Página 647 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Scale Method

Applies To

Report object.

Description

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 OnPrint or OnFormat event property for a report section, or the OnPage event property for a report.

The Scale method has the following arguments.

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.

See Also

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.

Page 648: Microsoft Access Language

Microsoft Access Language Reference Página 648 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Circle method, Event properties, Line method, Print method, PSet method, ScaleHeight, ScaleWidth properties, ScaleLeft, ScaleTop properties, ScaleMode property.

Example

The following example draws a circle with one scale, then uses the Scale method to change the scale and draw another circle with the new scale.

Private Sub Detail_Print(Cancel As Integer, PrintCount As Integer) DrawCircleEnd Sub

Sub DrawCircle() Dim sngHCtr As Single, sngVCtr As Single Dim sngNewH As Single, sngNewV As Single Dim sngRadius As Single

Me.ScaleMode = 3 ' Set scale to pixels. sngHCtr = Me.ScaleWidth / 2 ' Horizontal center. sngVCtr = Me.ScaleHeight / 2 ' Vertical center. sngRadius = Me.ScaleHeight / 3 ' Circle radius. ' Draw circle. Me.Circle (sngHCtr, sngVCtr), sngRadius ' New horizontal scale. sngNewH = Me.ScaleWidth * 0.9 ' New vertical scale. sngNewV = Me.ScaleHeight * 0.9 ' Change to new scale. Me.Scale(0, 0)-(sngNewH, sngNewV) ' Draw circle. Me.Circle (sngHCtr + 100, sngVCtr), sngRadius, RGB(0, 256, 0)End Sub

ScaleHeight, ScaleWidth Properties

Applies To

Report.

Description

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, or its output is saved to a file.

Setting

l The ScaleHeight property specifies a Single value used in a numeric expression to set the number of units for the vertical measurement of the page.

l The ScaleWidth property specifies a Single 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 by using a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Page 649: Microsoft Access Language

Microsoft Access Language Reference Página 649 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 one one-hundredth 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.

By using these properties and the related ScaleLeft and ScaleTop properties, you can set up a custom coordinate system with both positive and negative coordinates. All four of these Scale properties interact with the ScaleMode property in the following ways:

l Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

l Setting the ScaleMode property to a number greater than 0 changes the ScaleHeight and ScaleWidth properties to the new unit of measurement and sets the ScaleLeft and ScaleTop properties 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.

See Also

Circle method, CurrentX, CurrentY properties, Line method, Print method, PSet method, ScaleLeft, ScaleTop properties, ScaleMode property.

ScaleLeft, ScaleTop Properties

Applies To

Report.

Description

You can use the ScaleLeft and ScaleTop properties to specify the units for the horizontal and 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

Page 650: Microsoft Access Language

Microsoft Access Language Reference Página 650 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

l The ScaleLeft property specifies a Single 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.

l The ScaleTop property specifies a Single 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 by using a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

By using these properties and the related ScaleHeight and ScaleWidth properties, you can set up a custom coordinate system with both positive and negative coordinates. All four of these Scale properties interact with the ScaleMode property in the following ways:

l Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

l Setting the ScaleMode property to a number greater than 0 changes the ScaleHeight and ScaleWidth property settings to the new unit of measurement and sets the ScaleLeft and ScaleTop properties 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.

See Also

Circle method, Event properties, Line method, Print method, PSet method, Scale method, ScaleHeight, ScaleWidth properties, ScaleMode property.

ScaleMode Property

Applies To

Report.

Description

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, or its output is saved to a file.

Setting

The ScaleMode property uses the following settings.

Page 651: Microsoft Access Language

Microsoft Access Language Reference Página 651 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The property setting has an Integer value.

You can set the ScaleMode property by using a macro or a Visual Basic event procedure specified by a section's OnPrint property setting.

Remarks

By using the related ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties, you can create a custom coordinate system with both positive and negative coordinates. All four properties interact with the ScaleMode property in the following ways:

l Setting any other Scale property to any value automatically sets the ScaleMode property to 0.

l Setting the ScaleMode property to a number greater than 0 changes the ScaleHeight and ScaleWidth property settings to the new unit of measurement and sets the ScaleLeft and ScaleTop properties to 0. Also, the CurrentX and CurrentY property settings change to reflect the new coordinates of the current point.

See Also

Setting Description

0 Custom values used by one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties

1 (Default) Twips

2 Points

3 Pixels

4 Characters (horizontal = 120 twips per unit; vertical = 240 twips per unit)

5 Inches

6 Millimeters

7 Centimeters

Page 652: Microsoft Access Language

Microsoft Access Language Reference Página 652 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Circle method, CurrentX, CurrentY properties, Event properties, Line method, Print method, PSet method, Scale method, ScaleHeight, ScaleWidth properties, ScaleLeft, ScaleTop properties.

Example

The following example uses the Print method to display text on a report named Report1. It uses the TextWidth and TextHeight methods to center the text vertically and horizontally.

Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer) Dim rpt as Report Dim strMessage As String Dim intHorSize As Integer, intVerSize As Integer

Set rpt = Me strMessage = "DisplayMessage" With rpt 'Set scale to pixels, and set FontName and FontSize properties. .ScaleMode = 3 .FontName = "Courier" .FontSize = 24 End With ' Horizontal width. intHorSize = Rpt.TextWidth(strMessage) ' Vertical height. intVerSize = Rpt.TextHeight(strMessage) ' Calculate location of text to be displayed. Rpt.CurrentX = (Rpt.ScaleWidth/2) - (intHorSize/2) Rpt.CurrentY = (Rpt.ScaleHeight/2) - (intVerSize/2) ' Print text on Report object. Rpt.Print strMessageEnd Sub

ScaleTop Property

See ScaleLeft, ScaleTop Properties.

ScaleWidth Property

See ScaleHeight, ScaleWidth Properties.

Screen Object

Description

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

Page 653: Microsoft Access Language

Microsoft Access Language Reference Página 653 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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's 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 preceding example would return an error.

Properties

ActiveControl property, ActiveDatasheet property, ActiveForm property, ActiveReport property, Application property, MousePointer property, Parent property, PreviousControl property.

See Also

Control object, Form object, Report object, SelectObject action.

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

ScrollBars Property

Applies To

Form, Text Box control.

Description

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.

Page 654: Microsoft Access Language

Microsoft Access Language Reference Página 654 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the form's or control's property sheet, a macro, or Visual Basic.

For a text box, you can set the default for this property by using the default control style or the DefaultControl method in Visual Basic.

Remarks

If 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.

See Also

Modal property, NavigationButtons property, PopUp property, RecordSelectors property.

Section Property

Applies To

Setting Description Visual Basic

Neither (forms)None (text boxes)

(Default for text boxes) No scroll bars appear on the form or text box.

0

Horizontal Only (forms)

Horizontal scroll bar appears on the form. Not applicable to text boxes.

1

Vertical Only (forms)Vertical (text boxes)

Vertical scroll bar appears on the form or text box.

2

Both (forms) (Default for forms) Vertical and horizontal scroll bars appear on the form. Not applicable to text boxes.

3

Page 655: Microsoft Access Language

Microsoft Access Language Reference Página 655 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Page, Page Break control, Rectangle control, Report, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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. You can use Integer values or the constants listed below. It is recommended that you use the constants to make your code easier to read.

Setting Constant Description

0 acDetail Form detail section or report detail section

1 acHeader Form or report header section

2 acFooter Form or report footer section

3 acPageHeader Form or report page header section

4 acPageFooter Form or report page footer section

5 acGroupLevel1Header Group-level 1 header section (reports only)

6 acGroupLevel1Footer Group-level 1 footer section (reports only)

7 acGroupLevel2Header Group-level 2 header section (reports only)

Page 656: Microsoft Access Language

Microsoft Access Language Reference Página 656 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 page 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(acDetail).VisibleForms!Customers.Section(0).VisibleForms!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(acPageHeader).VisibleForms!Customers.Section(3).Visible

For controls, you can use the Section property to determine which section of a form or report a control is in. The following example uses the Section property to determine which section contains the CustomerID control.

Dim intSectionNumber As IntegerintSectionNumber = Forms!Customers!CustomerID.Section

See Also

CanGrow, CanShrink properties, FillColor property, ForceNewPage property, Height, Width properties, KeepTogether property-sections, NewRowOrCol property, SpecialEffect property, Visible property.

Selected Property

Applies To

List Box control.

Description

You can use the Selected property in Visual Basic to determine if an item in a list box is selected.

8 acGroupLevel2Footer Group-level 2 footer section (reports only)

Page 657: Microsoft Access Language

Microsoft Access Language Reference Página 657 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The Selected property is a zero-based array that contains the selected state of each item in a list box.

You can get or set the Selected property by 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. A multiple-selection list box bound to a field will always have a Value property equal to Null. You use the Selected property or the ItemsSelected collection to retrieve information about which items are selected.

You can use the Selected property to select items in a list box by using Visual Basic. For example, the following expression selects the fifth item in the list:

Me!Listbox.Selected(4) = True

See Also

Column property, ItemsSelected collection, ListIndex property, MultiSelect 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 cmdCopyItem command button.

Sub cmdCopyItem_Click() CopySelected MeEnd 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

Setting Description

True (–1) The list box item is selected.

False (0) The list box item isn't selected.

Page 658: Microsoft Access Language

Microsoft Access Language Reference Página 658 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Set ctlDest = frm!lstDestination For intCurrentRow = 0 To ctlSource.Listcount - 1 If ctlSource.Selected(intCurrentRow) Then strItems = strItems & ctlSource.Column(0, intCurrentRow) & ";" End If Next intCurrentRow ' Reset destination control's RowSource property. ctlDest.RowSource = "" ctlDest.RowSource = strItemsEnd Function

SelectObject Action

Description

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

Setting

The SelectObject action has the following arguments.

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's 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

Action argument

Description

Object Type The type of database object to select. Click Table, Query, Form, Report, Macro, or Module in 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 argument. This is a required argument, unless you set the In Database Window argument to Yes. If you set the In Database Window argument to Yes and leave the Object Name argument blank, Microsoft Access selects the tab in the Database window that corresponds to the database object you specify in the Object Type argument.

In Database Window

Specifies whether Microsoft Access selects the object in the Database window. Click Yes (to select the object in the Database window) or No (not to select the object in the Database window). The default is No.

Page 659: Microsoft Access Language

Microsoft Access Language Reference Página 659 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 (by using the Restore action) or maximize a window that contains an object you want to work with (by 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.

See Also

Restore action, SelectObject method, SetValue action.

SelectObject Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Argument Description

objecttype One of the following intrinsic constants:

Page 660: Microsoft Access Language

Microsoft Access Language Reference Página 660 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If you set the indatabasewindow argument to True and leave the objectname argument blank, you must include the objectname argument's comma. If you leave a trailing argument blank, don't use a comma following the last argument you specify.

Example

The following example selects the form Customers in the Database window:

DoCmd.SelectObject acForm, "Customers", True

SelHeight, SelWidth Properties

acFormacMacroacModuleacQueryacReportacTable

Note The constant acDefault, which appears in the Auto List Members list for this argument, is invalid for this argument. You must choose one of the constants listed above.

objectname A string expression that's the valid name of an object of the type selected by the objecttype argument. This is a required argument, unless you specify True (–1) for the indatabasewindow argument. If you specify True for the indatabasewindow argument and leave the objectname argument blank, Microsoft Access selects the tab in the Database window that corresponds to the database object you specify in the objecttype argument.

indatabasewindow Use True to select the object in the Database window. Use False (0) to select an object that's already open. If you leave this argument blank, the default (False) is assumed.

Page 661: Microsoft Access Language

Microsoft Access Language Reference Página 661 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Form, QueryDef object, Table, TableDef object.

Description

You can use the SelHeight property to specify or determine the number of selected rows (records) in the current selection rectangle in a table, query, or form datasheet, or the number of selected records in a continuous form. 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've 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

l The SelHeight property. A Long Integer value between 0 and the number of records in the datasheet or continuous form. The setting of this property specifies or returns the number of selected rows in the selection rectangle or the number of selected records in the continuous form.

l The SelWidth property. A Long Integer value between 0 and the number of columns in the datasheet. The setting of this property specifies or returns the number of selected columns in the selection rectangle.

These properties aren't available in Design view. These properties are only available by using a macro or Visual Basic.

Remarks

If there's no selection, the value returned by these properties will be zero. Setting either of these properties to 0 removes the selection from the datasheet or form.

If you've selected one or more records in the datasheet (using the record selectors), you can't change the setting of the SelWidth property (except to set it to 0). If you've selected one or more columns (using the column headings), you can't change the setting of the SelHeight property (except to set it to 0).

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's no selection, then the SelTop and SelLeft 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.

See Also

SelTop, SelLeft properties.

Example

Page 662: Microsoft Access Language

Microsoft Access Language Reference Página 662 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 lngNumRows, lngNumColumns, lngTopRow, and lngLeftColumn, 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 IfEnd Sub

SelLeft Property

See SelTop, SelLeft Properties.

SelLength, SelStart, SelText Properties

Applies To

Combo Box control, Text Box control.

Description

You can use these properties for tasks such as positioning the insertion point, establishing an insertion range, selecting parts of strings in a text box or combo box control, and deleting text.

l The SelLength property specifies or determines the number of characters selected in a text box or the text box portion of a combo box.

l The SelStart property specifies or determines the starting point of the selected text or the position of the insertion point if no text is selected.

l The SelText property returns a string containing the selected text. If no text is selected, the SelText property contains a Null value.

Setting

l The SelLength and SelStart properties use an Integer in the range 0 to the total number of characters in a text box or text box portion of a combo box.

l The SelText property uses a string expression that contains the text selected in the

Page 663: Microsoft Access Language

Microsoft Access Language Reference Página 663 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

control. If the control contains selected text when this property is set, the selected text is replaced by the new SelText setting.

You can set the SelLength and SelStart properties by using 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, 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.

See Also

SetFocus method, Text property.

Example

The following example uses two event procedures to search for text specified by a user. The text to search is set in the form's Load event procedure. The Click event procedure for the Find button (which the user clicks 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 ' SetFocus to text box. ctlTextToSearch.Text = "This company places large orders " _ & "twice a year for 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. With Me!Textbox1 strSearch = InputBox("Enter text to find:") ' Find string in text. intWhere = InStr(.Value, strSearch) If intWhere Then ' If found. .SetFocus .SelStart = intWhere - 1 .SelLength = Len(strSearch) Else ' Notify user. MsgBox "String not found." End If End WithEnd Sub

Page 664: Microsoft Access Language

Microsoft Access Language Reference Página 664 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

SelTop, SelLeft Properties

Applies To

Form, QueryDef object, Table, TableDef object.

Description

You can use the SelTop property to specify or determine which row (record) is topmost in the current selection rectangle in a table, query, or form datasheet, or which selected record is topmost in a continuous form. You can use the SelLeft property to specify or determine which column (field) is leftmost in the current selection rectangle. For example, if you've selected a group of rows and columns within Datasheet view of the Customers table, you can use the SelTop and SelLeft properties to determine the first row and first column selected in the selection rectangle.

Setting

l The SelTop property. A Long Integer value between 1 and the number of records in the datasheet or continuous form. The setting of this property specifies or returns the number of the topmost row in the current selection rectangle or the number of the topmost selected record in the continuous form.

l The SelLeft property. A Long Integer value between 1 and the number of columns in the datasheet. The setting of this property specifies or returns the number of the leftmost column in the current selection rectangle.

These properties aren't available in Design view. These properties are available only by using a macro or Visual Basic.

Remarks

If there's no selection, the value returned by these properties is the row and column of the cell with the focus.

If you've selected one or more records in the datasheet (using the record selectors), you can't change the setting of the SelLeft property. If you've selected one or more columns (using the column headings), you can't change the setting of the SelTop property.

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.

See Also

SelHeight, SelWidth properties.

Example

See the SelHeight, SelWidth properties example.

Page 665: Microsoft Access Language

Microsoft Access Language Reference Página 665 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

SelWidth Property

See SelHeight, SelWidth Properties.

SendKeys Action

Description

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

Setting

The SendKeys action has the following arguments.

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.

Note An error can occur if the Keystrokes argument contains incorrect syntax, misspelled text, or other values that aren't appropriate for the window the keystrokes are sent to.

You can use this action to enter information in a dialog box, particularly if you don't want to

Action argument

Description

Keystrokes The keystrokes you want Microsoft Access or the application to process. Enter the keystrokes in the Keystrokes box in the Action Arguments section of the Macro window. You can type up to 255 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.

Page 666: Microsoft Access Language

Microsoft Access Language Reference Página 666 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

interrupt the macro to respond manually to the dialog box. Some Microsoft Access actions, such as PrintOut 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

l 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.

l The timing of the keystrokes reaching Microsoft Access or another application can be tricky. As a result, it's recommended that if there's 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 255 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.

See Also

GoToControl action, KeyDown, KeyUp events, KeyPress event, PrintOut action, SelectObject action, SendKeys statement, SetValue action.

SendObject Action

Description

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 97 (*.xls), MS-DOS text (*.txt), rich-text (*.rtf), or HTML (*.html) format in messages for Microsoft Exchange, 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 has the following arguments.

Page 667: Microsoft Access Language

Microsoft Access Language Reference Página 667 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 with this argument, but leave the Object Name argument blank.

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 arguments 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 HTML (*.html), Microsoft Excel (*.xls), MS-DOS Text (*.txt), or Rich Text Format (*.rtf) in the Output Format box. Modules can be sent only in MS-DOS text format. If you leave this argument blank, Microsoft Access prompts you for the output format.

Note You can't include objects in Microsoft ActiveX Server (*.asp) or Microsoft IIS (*.htx, *.idc) format, although these selections are displayed in the list.

Page 668: Microsoft Access Language

Microsoft Access Language Reference Página 668 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 on the Number tab of the Regional Settings Properties dialog box in Windows Control Panel. If the mail application can't identify the recipients' names, the message isn't sent.

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 argument 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 argument blank, the Bcc line in the mail message is blank.

Action argument

Description

Subject The subject of the message. This text appears on the Subject line in the mail message. If you leave this argument 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 argument blank, no additional text is included in the mail message. If you leave the Object Type and Object Name arguments blank, you can use this argument to send a mail

Page 669: Microsoft Access Language

Microsoft Access Language Reference Página 669 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 Microsoft Office 97 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 Windows Notepad (for .txt files), and Microsoft Word (for .rtf files). For .html files, your default Internet browser (such as Microsoft Internet Explorer) starts.

The following rules apply when you use the SendObject action to include a database object in a mail message:

l 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.

l 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).

l For a text box bound to a Hyperlink field, the output file displays the hyperlink for all output formats except MS-DOS text (in this case, the hyperlink is just displayed as normal text).

l If you send a form in Form view, the included object always contains the form's Datasheet view.

l 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, .txt, and .html 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 with 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.

l Subreports are included in the object, but subforms aren't.l When you send a datasheet or form in HTML format, one .html file is created. When you

send a report in HTML format, one .html file is created for each page in the report.

message without a database object.

Edit Message

Specifies 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.

Template File

The path and file name of a file you want to use as a template for an .html file. The template file is a file containing HTML tags.

Page 670: Microsoft Access Language

Microsoft Access Language Reference Página 670 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Tip If you send the data in a report and the columns and rows of data in the included object don't align as in the report, the following tips may help:

l You can point to Size on the Format menu, then click To Fit to size the controls.l You should avoid overlapping controls or placing controls too close together.l You can point to Align on the Format menu, then click the appropriate command to align

the controls on the report. Controls that aren't aligned in the same row may be placed in separate rows in the included object, 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. The Send command, however, applies only to the active object. If you use the SendObject action, you can specify the object you want to send.

Note You can send the selected data with the Send command. However, this functionality isn't available with the SendObject action.

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

See Also

OutputTo action, SendObject method.

SendObject Method

Applies To

DoCmd object.

Description

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][, templatefile]

The SendObject method has the following arguments.

Argument Description

objecttype One of the following intrinsic constants:

Page 671: Microsoft Access Language

Microsoft Access Language Reference Página 671 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

acSendFormacSendModuleacSendNoObject (default)acSendQueryacSendReportacSendTable

objectname A string expression that's the valid name of an object of the type selected by 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 (the default constant, acSendNoObject, is assumed for the objecttype argument), Microsoft Access sends a message to the electronic mail application without an included database object.

If you run 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:

acFormatHTMLacFormatRTFacFormatTXTacFormatXLS

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.

Page 672: Microsoft Access Language

Microsoft Access Language Reference Página 672 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 on the Number tab of the Regional Settings Properties dialog box in Windows Control Panel. If the recipient names aren't recognized by the mail application, the message isn't sent.

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's included in the body of the mail message.

Page 673: Microsoft Access Language

Microsoft Access Language Reference Página 673 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

Modules can be sent only in MS-DOS Text format, so if you specify acSendModule 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.

See Also

OutputTo method.

Example

The following 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 acSendTable, "Employees", acFormatXLS, _ "Nancy Davolio; Andrew Fuller", "Joan Weber", , _ "Current Spreadsheet of Employees", , False

SetFocus Method

Applies To

ActiveX control, Bound Object Frame control, Check Box control, Combo Box control, Command Button control, Control object, Form object, Image control, List Box control, Option Button control, Option Group control, Page, Subform/Subreport control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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.

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.

templatefile A string expression that's the full name, including the path, of the file you want to use as a template for an HTML file.

Page 674: Microsoft Access Language

Microsoft Access Language Reference Página 674 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Syntax

object.SetFocus

The SetFocus method has the following argument.

Remarks

You can 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 the 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 Enabled properties to False (0) 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's 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 (–1) 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.

See Also

GotFocus, LostFocus events, GoToControl action, SelectObject action.

Argument Description

object A Form object that represents a form, or a Control object that represents a control on the active form or datasheet.

Page 675: Microsoft Access Language

Microsoft Access Language Reference Página 675 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Example

The following example uses the SetFocus method to move the focus to an EmployeeID text box on an Employees form:

Forms!Employees!EmployeeID.SetFocus

SetMenuItem Action

Description

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.

Note The SetMenuItem action works only with custom menu bars and global menu bars created by using menu bar macros. The SetMenuItem action is included in this version of Microsoft Access only for compatibility with previous versions. It doesn't work with the new command bars functionality. However, you can use the Enabled and State properties in Visual Basic to disable or enable and check or uncheck items on the new menu bars, toolbars, and shortcut menus.

Setting

The SetMenuItem action has 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. Enter the index value in the Menu Index box in the Action Arguments section of the Macro 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.

Page 676: Microsoft Access Language

Microsoft Access Language Reference Página 676 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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).

Action argument

Description

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 by 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 by 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).

Page 677: Microsoft Access Language

Microsoft Access Language Reference Página 677 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

The SetMenuItem action works only on a custom menu bar or global menu bar for the active window. It doesn't work on the built-in Microsoft Access menu bars, and if the active window doesn't 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've defined one, replaces the built-in menu bar for all Microsoft Access windows, except where you've 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.

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

See Also

AddMenu action, DoMenuItem action, Enabled property ("Microsoft Office Language Reference" in Volume 5), MenuBar property, SetMenuItem method.

SetMenuItem Method

Applies To

DoCmd object.

Description

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.

Note The SetMenuItem method works only with custom menu bars and global menu bars created by using menu bar macros. The SetMenuItem method is included in this version of Microsoft Access only for compatibility with previous versions. It doesn't work with the new command bars functionality.

Syntax

DoCmd.SetMenuItem menuindex[, commandindex][, subcommandindex][, flag]

Flag The state you want to set the command or subcommand to. Click Gray (to disable the command — 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.

Page 678: Microsoft Access Language

Microsoft Access Language Reference Página 678 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The SetMenuItem method has the following arguments.

Argument Description

menuindex An integer, counting from 0, that's 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's the valid index of a command on the menu selected by 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's the valid index of a subcommand in the submenu selected by 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:

acMenuCheckacMenuGrayacMenuUncheckacMenuUngray (default)

Page 679: Microsoft Access Language

Microsoft Access Language Reference Página 679 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

AddMenu action, DoMenuItem method, MenuBar property, SetMenuItem action.

Example

The following 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

SetOption Method

See GetOption, SetOption methods.

SetValue Action

Description

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 has the following arguments.

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

Action argument

Description

Page 680: Microsoft Access Language

Microsoft Access Language Reference Página 680 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note To use the Expression Builder to create an expression for either of these arguments, click the Build button to the right of the Item or 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 by 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 by 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.

Item The name of the field, control, or property whose value you want to set. Enter the field, control, or property name in the Item box in the Action Arguments section of the Macro window. 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.

Page 681: Microsoft Access Language

Microsoft Access Language Reference Página 681 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 by 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 the SetValue action 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:

l Bound controls and calculated controls on reports.l 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 by using the SetValue action in a macro doesn't 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 by using Visual Basic.

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

See Also

RepaintObject action, SendKeys action.

SetWarnings Action

Description

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

Setting

The SetWarnings action has the following argument.

Page 682: Microsoft Access Language

Microsoft Access Language Reference Página 682 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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) — for example, any dialog box that requires you to enter text or select one of several options.

Carrying out this action with the Warnings On argument set to No has the same effect as pressing ENTER whenever a warning or message box is displayed. Typically, an OK or Yes button 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's 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.

See Also

Echo action, SetWarnings method.

SetWarnings Method

Applies To

DoCmd object.

Description

Action argument

Description

Warnings On Specifies whether system messages are displayed. Click Yes (to turn on system messages) or No (not to turn off system messages) in the Warnings On box in the Action Arguments section of the Macro window. The default is No.

Page 683: Microsoft Access Language

Microsoft Access Language Reference Página 683 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 has the following argument.

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.

See Also

Echo method (Application object), Echo method (DoCmd object).

Example

The following example turns the display of system messages off:

DoCmd.SetWarnings False

ShortcutMenu Property

Applies To

Form.

Description

You can use the ShortcutMenu property to specify whether a shortcut menu is displayed when you right-click an object on a form. For example, you might want to disable a shortcut menu to prevent the user from changing the form's underlying record source by using one of the filtering

Argument Description

warningson Use True (–1) to turn on the display of system messages and False (0) to turn it off.

Page 684: Microsoft Access Language

Microsoft Access Language Reference Página 684 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

commands on the form's shortcut menu.

Setting

The ShortcutMenu property uses the following settings.

You can set this property by using the form's property sheet, a macro, or Visual Basic.

Remarks

This property controls the displaying of the shortcut menus for a form and for any of its controls. If the ShortcutMenu property is set to No, shortcut menus aren't displayed when you right-click a form or any of its controls.

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.

See Also

AllowFilters property, ShortcutMenuBar property, StartupShortcutMenuBar property.

Example

The following example disables the shortcut menus for the Invoice form and its controls:

Forms!Invoice.ShortcutMenu = False

ShortcutMenuBar Property

Applies To

Application object, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Image control, Label control, List Box control, Option Button control, Option Group control, Page, Report, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Setting Description Visual Basic

Yes (Default) Shortcut menus are displayed.

True (–1)

No Shortcut menus aren't displayed.

False (0)

Page 685: Microsoft Access Language

Microsoft Access Language Reference Página 685 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the ShortcutMenuBar property to specify the shortcut menu that will appear when you right-click on a form, report, or control on a form. You create these shortcut menus by pointing to Toolbars on the View menu and then clicking Customize.

Note The ShortcutMenuBar property applies only to controls on a form, not controls on a report.

You can also use the ShortcutMenuBar property to specify the menu bar macro that will be used to display a shortcut menu for a datasheet, form, form control, or report.

Note In previous versions of Microsoft Access, you created a custom shortcut menu by setting the ShortcutMenuBar property to the name of a menu bar macro. You then created a macro group containing the commands for this menu. This functionality is still supported in Microsoft Access 97. However, it is strongly recommended that you use the new Customize dialog box, available by pointing to Toolbars on the View menu, and then clicking Customize, to create custom shortcut menus.

Setting

Enter the name of the shortcut menu you want to display. A shortcut menu can be any command bar whose Type property is set to Popup. If you leave the ShortcutMenuBar property setting blank, Microsoft Access displays the built-in (default) shortcut menu or the application's global shortcut menu. If you set the ShortcutMenuBar property to a value that isn't the name of an existing shortcut menu or menu bar macro, the form, form control, or report won't have a shortcut menu (the default shortcut menu won't be shown).

You can set this property by using the object's property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property by using a string expression that is the name of the shortcut menu you want to display.

To display the built-in shortcut menu for a database, form, form control, or report by using a macro or Visual Basic, set the property to a zero-length string (" ").

Remarks

You create a custom shortcut menu by first creating a toolbar that includes all the commands you want to appear on your custom shortcut menu. Then open the Toolbar Properties dialog box by selecting the toolbar in the Customize dialog box and clicking the Properties button. In the Toolbar Properties dialog box, set the Type property to Popup. This toolbar will now be available in the ShortcutMenuBar property box in the property sheet for a form, form control, or report.

When used with the Application object, the ShortcutMenuBar property enables you to display a custom shortcut menu as a global shortcut menu. However, if you've set the ShortcutMenuBar property for a form, form control, or report in the database, the custom shortcut menu of that object will be displayed in place of the database's global shortcut menu. You can display a different custom shortcut menu for a specific form, form control, or report by setting its ShortcutMenuBar property to a different shortcut menu. When the form, form control, or report has the focus, the custom shortcut menu for that object is displayed when the user clicks the right mouse button; otherwise, the global shortcut menu for the database is displayed.

Shortcut menus aren't available to any object if the AllowShortcutMenus property is set to False

Page 686: Microsoft Access Language

Microsoft Access Language Reference Página 686 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(0).

See Also

AddMenu action, AllowShortcutMenus property, MenuBar property, ShortcutMenu property.

ShowAllRecords Action

Description

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 have any arguments.

Remarks

You can 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.

See Also

ApplyFilter action, OpenForm action, RepaintObject action, Requery action, ShowAllRecords method.

ShowAllRecords Method

Applies To

DoCmd object.

Description

Page 687: Microsoft Access Language

Microsoft Access Language Reference Página 687 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 has no arguments.

See Also

ApplyFilter method, OpenForm method, Recalc method, Refresh method, Repaint method, RepaintObject method, Requery method (Control or Form object), Requery method ("DAO Language Reference"), Requery method (DoCmd object), ShowAllRecords action.

ShowToolbar Action

Description

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).

Note The ShowToolbar action affects only toolbars, not menu bars or shortcut menus.

Setting

The ShowToolbar action has the following arguments.

Action argument

Description

Toolbar Name

The name of the toolbar you want to display or hide. The Toolbar Name box in the Action Arguments section of the Macro window 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.

Page 688: Microsoft Access Language

Microsoft Access Language Reference Página 688 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can use this action in a macro with conditional expressions to display or hide one or more toolbars depending on certain conditions.

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 pointing to Toolbars on the View menu and clicking Customize, then selecting or clearing a specific toolbar on the Toolbars tab of the Customize dialog box. 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.

If the Allow Built-in Toolbars check box in the Startup dialog box (available by clicking Startup on the Tools menu) is cleared, 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 Specifies whether to display or hide the toolbar and in which views to display or hide 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.

Page 689: Microsoft Access Language

Microsoft Access Language Reference Página 689 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The built-in toolbars are also not available to display or hide by using this action if you set the AllowBuiltInToolbars property to False (0) in Visual Basic, or if you set the Allow Built-in Toolbars option to False in Visual Basic by using the SetOption method.

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

See Also

Activate, Deactivate events, GetOption, SetOption methods, ShowToolbar method.

ShowToolbar Method

Applies To

DoCmd object.

Description

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.

Note The ShowToolbar method affects only toolbars, not menu bars or shortcut menus.

Syntax

DoCmd.ShowToolbar toolbarname[, show]

The ShowToolbar method has the following arguments.

(continued)

Argument Description

toolbarname A string expression that's the valid name of a Microsoft Access built-in toolbar or a custom toolbar you've created.

If you run 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.

Page 690: Microsoft Access Language

Microsoft Access Language Reference Página 690 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

If you leave the show argument blank, don't use a comma following the toolbarname argument.

See Also

AllowBuiltInToolbars property, GetOption, SetOption methods, ShowToolbar action.

Example

The following example displays the custom toolbar named CustomToolbar in all Microsoft Access windows that become active:

DoCmd.ShowToolbar "CustomToolbar", acToolbarYes

SizeMode Property

Applies To

Bound Object Frame control, Chart control, Image control, Unbound Object Frame control.

Description

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.

show One of the following intrinsic constants:

acToolbarNoacToolbarWhereAppropacToolbarYes (default)

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

Page 691: Microsoft Access Language

Microsoft Access Language Reference Página 691 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the SizeMode property in a property sheet, in a macro, or by using Visual Basic. You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

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.

See Also

Action property, Resize event.

Example

See the Action property example.

SizeToFit Method

Applies To

Bound Object Frame control, Check Box control, Combo Box control, Control object, Image control, Label control, List Box control, Page, Rectangle control, Text Box control.

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.

acOLESizeClip (0)

Stretch Sizes the object to fill the control. This setting may distort the proportions of the object.

acOLESizeStretch (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.

acOLESizeZoom (3)

Page 692: Microsoft Access Language

Microsoft Access Language Reference Página 692 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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 has the following argument.

Remarks

The use of 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.

You can 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.

See Also

Caption property, CreateControl, CreateReportControl functions, CreateForm, CreateReport functions.

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

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.

Page 693: Microsoft Access Language

Microsoft Access Language Reference Página 693 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

' 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.SizeToFitEnd Sub

SortOrder Property

Applies To

Report.

Description

You use the SortOrder property to specify the sort order for fields and expressions in a report. 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.

You can set the SortOrder property by using the Sorting And Grouping box, a macro, or Visual Basic.

In Visual Basic, you set the SortOrder property in report Design view or in the Open event procedure of a report by using the GroupLevel property.

See Also

CreateGroupLevel function, GroupHeader, GroupFooter properties, GroupInterval property, GroupLevel property, GroupOn property, KeepTogether property-groups.

Example

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)

Page 694: Microsoft Access Language

Microsoft Access Language Reference Página 694 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See the GroupInterval property example.

Source Property

Applies To

Action query, Crosstab query, Parameter query, Select query, SQL-Specific query.

Description

You can use the Source property to specify the source connection string and source database for a query's source table or query. This is necessary if you're accessing data in an external table without linking the table.

Tip 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 by using a string expression. You can't set this property in code directly. It's set when you create a new query by using an SQL statement. The FROM clause in the SQL statement corresponds to the Source property setting.

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 file name extension automatically.

C:\Accts\Customers

dBASE The database type and path. For a list of specifiers, see the DAO Connect property.

dBASE IV;DatabaseTable=C:\DBDATA

Page 695: Microsoft Access Language

Microsoft Access Language Reference Página 695 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

You can set this property by using 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 source 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 source table or query.

See Also

Connect property ("DAO Language Reference"), DestConnectStr, DestinationDB, DestinationTable properties, SourceConnectStr, SourceDatabase properties.

Example

The following example sets the RowSource property for the lstContact list box control to a field in a dBASE IV table.

Dim strGetSQL AS StringstrGetSQL = "SELECT Customer.COMPANYNAM, Customer.PHONE FROM Customer " _ & "IN 'c:\dbdata'[dBASE IV;];"Me.lstContact.RowSource = strGetSQL

In the next example, the source of data for the query is a dBASE IV table named Customer in the C:\Dbdata folder. You can enter this SQL statement in SQL view of a Query window.

SELECT Customer.COMPANYNAM, Customer.PHONEFROM Customer IN 'c:\dbdata'[dBASE IV;];

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;

Page 696: Microsoft Access Language

Microsoft Access Language Reference Página 696 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

SourceConnectStr, SourceDatabase Properties

Applies To

Action query, Crosstab query, Parameter query, Select query.

Description

You can use these properties to access external data when you can't link the external tables to your database.

l The SourceConnectStr property specifies the name of the application used to create an external database.

l The SourceDatabase property specifies the external database in which the source 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's 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 instead of the SourceConnectStr and SourceDatabase properties.

Remarks

You must use the SourceConnectStr and SourceDatabase properties to access tables from external databases that were created in applications that don't use linked tables.

The following are examples of these property settings:

l For a Microsoft Access database, the SourceDatabase property setting is the path and database name (for example, C:\Accounts\Customers). Microsoft Access adds the file name extension automatically. The SourceConnectStr property doesn't have a value for a Microsoft Access database.

l For a database created by a product such as Paradox, the SourceDatabase property setting is the path (for example, C:\Pdoxdata). The SourceConnectStr property setting is the specifier for the database type (for example, Paradox 3.x;). For a list of specifiers, see the DAO Connect property.

l The following example uses dBASE IV tables in the C:\Dbdata directory as the source of data for the query.

SELECT Customer.COMPANYNAM, Orders.ORDERID, Orders.ORDERDATE

Page 697: Microsoft Access Language

Microsoft Access Language Reference Página 697 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

FROM Customer INNER JOIN OrdersON Customer.CUSTOMERID = Orders.CUSTOMERIDIN 'C:\Dbdata'[dBASE IV;];

l 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.

For more information about accessing data in ODBC databases, see Chapter 18, "Accessing External Data," in Building Applications with Microsoft Access 97.

SourceDoc Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

You can use the SourceDoc property to specify the file to create a link to or to embed when you create a linked object or embedded object by using the Action property in Visual Basic.

Setting

For an embedded object, enter the full path and file name 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 file name of the file to create a link to and set the Action property to acOLECreateLink.

You can set this property in a property sheet, in a macro, or by using Visual Basic.

Note While this property appears in the property sheet, it takes effect only after the Action property is set in a macro or by using Visual Basic.

Remarks

You can use the SourceDoc property to specify the file to create a link to and the control's SourceItem property to specify the data within that file. If you want to create a link to 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:

Page 698: Microsoft Access Language

Microsoft Access Language Reference Página 698 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

"C:\Work\Qtr1\Revenue.xls!R1C1:R30C15"

See Also

Action property, Class property, OLEType property, OLETypeAllowed property, SourceItem property.

Example

See the Action property example.

SourceItem Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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 by 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 was used to create the object.

You can set this property by using the control's property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property by 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.

See Also

Action property, Class property, OLEType property, OLETypeAllowed property, SourceDoc property.

Example

See the Action property example.

Page 699: Microsoft Access Language

Microsoft Access Language Reference Página 699 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

SourceObject Property

Applies To

Chart control, Subform/Subreport control, Unbound Object Frame control.

Description

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 file name 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 by using the control's property sheet, a macro, or Visual Basic.

In Visual Basic, you set this property by 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.

See Also

Class property, LinkChildFields, LinkMasterFields properties, OLEType property, Parent property, SourceDoc property.

Example

The following example displays the name of the form that is the source of the ProductList subform control in the Debug window.

Debug.Print Forms!Categories! _

Page 700: Microsoft Access Language

Microsoft Access Language Reference Página 700 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

[Product List].SourceObject

SpecialEffect Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Form section, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Rectangle control, Report section, Subform/Subreport control, Text Box control, Unbound Object Frame control.

Description

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

Page 701: Microsoft Access Language

Microsoft Access Language Reference Página 701 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the Special Effect button on the Formatting (Form/Report) toolbar, the object's property sheet, a macro, or Visual Basic.

For controls, you can set the default for this property by using the default control style or the DefaultControl method in Visual Basic.

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 to Flat.

Note When you set the SpecialEffect property of a text box to Shadowed, the vertical height of the text display area is reduced. You can adjust the Height property of the text box to increase the size of the text display area.

See Also

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

Shadowed 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

Page 702: Microsoft Access Language

Microsoft Access Language Reference Página 702 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

BackStyle property, BorderColor property, BorderStyle property, BorderWidth property.

StartupForm Property

Applies To

Database object.

Description

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's the name of a form in the current database.

The easiest way to set this property is by using the Display Form option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the StartupForm property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

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 shouldn't 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 doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AppIcon property, AppTitle property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference"), StartupMenuBar property, StartupShortcutMenuBar property, StartupShowDBWindow property, StartupShowStatusBar property.

Example

See the AllowBreakIntoCode property example.

Page 703: Microsoft Access Language

Microsoft Access Language Reference Página 703 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

StartupMenuBar Property

Applies To

Database object.

Description

You can use the StartupMenuBar property to specify a custom menu bar to use as the global menu bar for your application. For example, you can use the StartupMenuBar property to display a custom menu bar that doesn't contain the Security menu. This prevents a user from accessing any of the Security menu commands from the menu bar. You can also specify a menu bar macro that displays the custom menu bar you want to use as the global menu bar.

Setting

The StartupMenuBar property is a string expression that's the name of a custom menu bar or menu bar macro in the current database.

The easiest way to set this property is by using the Menu Bar option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the StartupMenuBar property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

If you are setting the StartupMenuBar property, you shouldn't 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 bar set by the StartupMenuBar property.

You can also create custom menu bars by 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 (which it is by default), Microsoft Access displays the built-in menu bar. If this property is set to the name of a custom menu bar, then the setting of the AllowFullMenus property has no effect (the built-in full menus are replaced by the global menu bar).

Setting this property has the same effect as setting the MenuBar property of the Application object (except the MenuBar property setting takes effect immediately).

If the Use Access Special Keys check box in the Startup dialog box is selected, or if the AllowSpecialKeys property is set to True (–1), users can still press CTRL+F11 to toggle between the global menu bar and the built-in menu bar.

Page 704: Microsoft Access Language

Microsoft Access Language Reference Página 704 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AppIcon property, AppTitle property, CreateProperty method ("DAO Language Reference"), MenuBar property, Properties collection ("DAO Language Reference"), StartupForm property, StartupShortcutMenuBar property, StartupShowDBWindow property, StartupShowStatusBar property.

StartupShortcutMenuBar Property

Applies To

Database object.

Description

You can use the StartupShortcutMenuBar property to specify a custom shortcut menu to use as the global shortcut menu for your application. You can also specify a menu bar macro that displays the custom shortcut menu you want to use as the global shortcut menu.

Setting

The StartupShortcutMenuBar property is a string expression that's the name of a custom shortcut menu or a menu bar macro that displays a custom shortcut menu.

The easiest way to set this property is by using the Shortcut Menu Bar option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the StartupShortcutMenuBar property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

If you are setting the StartupShortcutMenuBar property, you shouldn't 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 menus by using the ShortcutMenuBar property for forms, reports, and form controls. These custom shortcut menus are displayed when you right-click a specific form, report, or form control, and replace the global shortcut menu in those cases.

If this property is blank, Microsoft Access displays the built-in shortcut menus.

Setting this property has the same effect as setting the ShortcutMenuBar property of the

Page 705: Microsoft Access Language

Microsoft Access Language Reference Página 705 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Application object (except the ShortcutMenuBar property setting takes effect immediately).

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AllowFullMenus property, AllowShortcutMenus property, AppIcon property, AppTitle property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference").

StartupShowDBWindow Property

Applies To

Database object.

Description

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 uses the following settings.

The easiest way to set this property is by using the Display Database Window option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the StartupShowDBWindow property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

You can set the StartupShowDBWindow property to False to hide the Database window so the user can't see the tables, queries, macros, and modules within your database.

Setting Description

True (–1) Display the Database window at startup.

False (0) Don't display the Database window at startup.

Page 706: Microsoft Access Language

Microsoft Access Language Reference Página 706 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

If the Use Access Special Keys check box in the Startup dialog box is selected, or if the AllowSpecialKeys property is set to True, users can still press the F11 key to display the Database window.

Even if you set both the StartupShowDBWindow and AllowSpecialKeys properties to False, it's possible that a user can still access the Database window. This can happen if a user tries more than once to open the same database from the list of most-recently-used databases, which automatically appears on the File menu. To prevent users from accessing this list, replace the File menu with your own custom menu.

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AppIcon property, AppTitle property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference"), StartupForm property, StartupMenuBar property, StartupShortcutMenuBar property, StartupShowStatusBar property.

Example

See the AllowBreakIntoCode property example.

StartupShowStatusBar Property

Applies To

Database object.

Description

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 don't want to display any status messages in your application.

Setting

The StartupShowStatusBar property uses the following settings.

Setting Description

True (–1) Display the status bar at startup.

False (0) Don't display the status bar at startup.

Page 707: Microsoft Access Language

Microsoft Access Language Reference Página 707 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The easiest way to set this property is by using the Display Status Bar option in the Startup dialog box, available by clicking Startup on the Tools menu. You can also set this property by using a macro or Visual Basic.

To set the StartupShowStatusBar property by using a macro or Visual Basic, you must first either set the property in the Startup dialog box once or create the property by using the CreateProperty method and append it to the Properties collection of the Database object.

Remarks

Setting this property affects the display of the status bar only for the current database. You can also control whether the status bar is shown or hidden by default for all Microsoft Access databases. To do this click Options on the Tools menu, click the View tab, and then select or clear the Status Bar check box under Show. The current database won't display a status bar if any of the following is true: the Status Bar check box in the Options dialog box is cleared; the Display Status Bar check box in the Startup dialog box is cleared; or the StartupShowStatusBar property is set to False.

This property's setting doesn't take effect until the next time the application database opens.

See Also

AllowBreakIntoCode property, AppIcon property, AppTitle property, CreateProperty method ("DAO Language Reference"), Properties collection ("DAO Language Reference"), StartupForm property, StartupMenuBar property, StartupShortcutMenuBar property, StartupShowDBWindow property, StatusBarText property.

Example

See the AllowBreakIntoCode property example.

StatusBarText Property

Applies To

Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Page, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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, not controls on a report.

Setting

You set the StatusBarText property by using a string expression up to 255 characters long.

Page 708: Microsoft Access Language

Microsoft Access Language Reference Página 708 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using the control's property sheet, a macro, or Visual Basic.

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.

Note You can also use the ControlTipText property to display a ScreenTip for a control.

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.

For a control containing a hyperlink, the status bar shows the hyperlink address when the mouse pointer is over the control if the Show Hyperlink Addresses In Status Bar box is selected. This check box is located on the Hyperlinks/HTML tab of the Options dialog, available by clicking Options on the Tools menu. When you're editing the control, the status bar shows the text that is the setting of the StatusBarText property.

See Also

Caption property, ControlTipText property, Description property.

StopAllMacros Action

Description

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

Setting

The StopAllMacros action doesn't have 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 clicks 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.

Page 709: Microsoft Access Language

Microsoft Access Language Reference Página 709 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

This action isn't available in Visual Basic.

See Also

Echo action, SetWarnings action, StopMacro action.

StopMacro Action

Description

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

Setting

The StopMacro action doesn't have 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 isn't available in Visual Basic.

See Also

Echo action, SetWarnings action, StopAllMacros action.

StringFromGUID Function

Description

The StringFromGUID function converts a GUID, which is an array of type Byte, to a string.

Syntax

StringFromGUID(guid)

Page 710: Microsoft Access Language

Microsoft Access Language Reference Página 710 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The StringFromGUID function has the following argument.

Remarks

The Microsoft Jet database engine stores GUIDs as arrays of type Byte. However, Microsoft Access can't return Byte data from a control on a form or report. In order to return the value of a GUID from a control, you must convert it to a string. To convert a GUID to a string, use the StringFromGUID function. To convert a string back to a GUID, use the GUIDFromString function.

For example, you may need to refer to a field that contains a GUID when using database replication. To return the value of a control on a form bound to a field that contains a GUID, use the StringFromGUID function to convert the GUID to a string.

Note that in order to bind a control to the s_GUID field of a replicated table, you must click Options on the Tools menu and select the System Objects check box on the View tab of the Options dialog box.

See Also

GUIDFromString function.

Example

The following example returns the value of the s_GUID control on an Employees form in string form and assigns it to a string variable. The s_GUID control is bound to the s_GUID field, one of the system fields added to each replicated table in a replicated database.

Sub StringValueOfGUID() Dim ctl As Control, strGUID As String

Set ctl = Forms!Employees!s_GUID Debug.Print TypeName(ctl.Value) strGUID = StringFromGUID(ctl.Value) Debug.Print TypeName(strGUID)End Sub

Style Property

Applies To

Tab control.

Argument Description

guid An array of Byte data used to uniquely identify an application, component, or item of data to the operating system.

Page 711: Microsoft Access Language

Microsoft Access Language Reference Página 711 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the Style property to specify or determine the appearance of tabs on a tab control.

Setting

The Style property uses the following settings.

You can set the Style property by using the tab control's property sheet, a macro, or Visual Basic.

You can also set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

You can set the Style property in any view.

Remarks

When the tab control's Style property is set to Tabs or Buttons, the appearance of the tabs is determined by the TabFixedHeight, TabFixedWidth, and MultiRow properties.

You could set the tab control's Style property to None if you wanted complete control over when a user could move between tabs. In prior versions of Microsoft Access, wizard dialogs were created by using multiple-page forms. You can now use a tab control create your own wizard with each page of the wizard contained on a separate page of a tab control with its Style property set to None.

See Also

MultiRow property, Style property, TabFixedHeight, TabFixedWidth properties.

SysCmd Function

Description

Setting Description Visual Basic

Tabs (Default) Tabs appear as tabs. acTabs

Buttons Tabs appear as buttons. acButtons

None No tabs appear in the control. acNone

Page 712: Microsoft Access Language

Microsoft Access Language Reference Página 712 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the SysCmd function to perform one of the following functions:

l Display a progress meter or optional specified text in the status bar.l Return information about Microsoft Access and its associated files.l 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 has the following arguments.

Argument Description

action One of the following intrinsic constants identifying the type of action to take.

The following set of constants applies to a progress meter. The SysCmd function 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.

Page 713: Microsoft Access Language

Microsoft Access Language Reference Página 713 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 the text argument.

acSysCmdClearStatus Resets the status bar text.

The following set of constants provides information about Microsoft Access.

acSysCmdRuntime Returns True (–1) 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.

Page 714: Microsoft Access Language

Microsoft Access Language Reference Página 714 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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).

The following 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. This argument is required when the action argument is acSysCmdInitMeter, acSysCmdUpdateMeter, or acSysCmdSetStatus; this argument isn't valid for other action argument values.

value A numeric expression that controls the display of the progress meter. This argument is required when the action argument is acSysCmdInitMeter; this argument isn't valid for other action argument values.

objecttype One of the following intrinsic constants:

Page 715: Microsoft Access Language

Microsoft Access Language Reference Página 715 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 argument, and the text and value arguments. When the action argument is acSysCmdInitMeter, the value argument is the maximum value of the meter, or 100 percent.

To update the meter to show the progress of the operation, call the SysCmd function with the acSysCmdUpdateMeter action argument and the value argument. When the action argument is acSysCmdUpdateMeter, the SysCmd function 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's displayed in the status bar by calling the SysCmd function with the acSysCmdSetStatus action argument 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 by using a proportional font, the actual number of characters you can display is determined by the total width of all the characters specified by the text argument.

acTableacQueryacFormacReportacMacroacModule

This argument is required when the action argument is acSysCmdGetObjectState; this argument isn't valid for other action argument values.

objectname A string expression that is the valid name of a database object of the type specified by the objecttype argument. This argument is required when the action argument is acSysCmdGetObjectState; this argument isn't valid for other action argument values.

Page 716: Microsoft Access Language

Microsoft Access Language Reference Página 716 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 the action argument is acSysCmdInitMeter, the SysCmd function ignores the text and doesn't display anything in the status bar. If the text is longer than the status bar and the action argument is acSysCmdSetStatus, the SysCmd function 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 the SysCmd function with the acSysCmdSetStatus action argument, the SysCmd function automatically removes the meter.

Call the SysCmd function 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 probably won't need an .ini file with your Microsoft Access application. The acSysCmdIniFile action argument exists for compatibility with earlier versions of Microsoft Access.

Call the SysCmd function with the acSysCmdGetObjectState action argument 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 the SysCmd function to determine the state of the table.

The SysCmd function with the acSysCmdGetObjectState action argument can return any combination of the following constants.

Note If the object referred to by the objectname argument is either not open or doesn't exist, the SysCmd function returns a value of zero.

Constant State of database object

acObjStateOpen Open

acObjStateNew New

acObjStateDirty Changed but not saved

Page 717: Microsoft Access Language

Microsoft Access Language Reference Página 717 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Also

CurrentObjectType, CurrentObjectName properties.

Example

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) & "..." varReturn = 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 varReturn = SysCmd(acSysCmdClearStatus) 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 FunctionCloseObjects: On Error Resume Next rst.Close dbs.Close On Error GoTo 0 DoCmd.Hourglass False ReturnEnd Function

The next example illustrates how you can use the SysCmd function with the acSysCmdGetObjectState action argument to determine the state of the active database object.

Dim intObjType As Integer, strObjName As String, intObjState As Integer

intObjType = Application.CurrentObjectTypestrObjName = Application.CurrentObjectName

Page 718: Microsoft Access Language

Microsoft Access Language Reference Página 718 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

intObjState = SysCmd(acSysCmdGetObjectState, intObjType, strObjName)If intObjState <> 0 Then . . .End If

TabFixedHeight, TabFixedWidth Properties

Applies To

Tab control.

Description

You can use the TabFixedHeight and TabFixedWidth properties to specify or determine the height and width of the tabs on a tab control.

Setting

The TabFixedHeight and TabFixedWidth property settings are a value that represents the height and width of tabs in the unit of measurement specified in the Regional Settings Properties dialog box in Windows Control Panel. If you set these properties to zero, the tabs automatically adjust to the height or width of the tab contents.

You can set these properties by using the tab control's property sheet, a macro, or Visual Basic.

You can also set the default for these properties by using a control's default control style or the DefaultControl method in Visual Basic.

In Visual Basic these properties use a Long Integer value representing the height or width of the tabs in twips and can be set in any view.

Note To use a unit of measurement different from the setting in the Regional Settings Properties dialog box in Windows Control Panel, specify the unit, such as cm or in (for example, 5 cm or 3 in).

Remarks

You can't change the color of a tab control. If the tabs don't cover the width of the tab control, the area behind the tabs is displayed. If you place a tab control on an object with a different color than the tab control, you should make sure that the tabs cover the control's background area.

See Also

Style property.

TabIndex Property

Page 719: Microsoft Access Language

Microsoft Access Language Reference Página 719 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

ActiveX control, Bound Object Frame control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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, not controls on a report.

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 by using the control's property sheet, a macro, or Visual Basic.

Note You can also set the tab order of controls on a form by using the Tab Order command on the View menu. This also sets the TabOrder property for the controls.

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 — even if you change the TabIndex property setting for the text box.

If you press an access key for a control such as a label that doesn't have a TabIndex property (and thus isn't in the tab order), the focus moves to the next control in the tab order that can receive the focus.

See Also

AutoTab property, Cycle property, TabStop property.

Example

The following example reverses the tab order of a command button and a text box. Because

Page 720: Microsoft Access Language

Microsoft Access Language Reference Página 720 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 = 1End Sub

TabStop Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, List Box control, Option Button control, Option Group control, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

You can use the TabStop property to specify whether you can use the TAB key to move the focus to a control in Form view.

Note The TabStop property applies only to controls on a form, not controls on a report.

This property doesn't apply to check box, option button, or toggle button controls when they appear in an option group. It applies only to the option group itself.

Setting

The TabStop property uses the following settings.

You can set this property by 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

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)

Page 721: Microsoft Access Language

Microsoft Access Language Reference Página 721 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 move through the controls by pressing TAB, even if their TabStop properties are set to Yes.

As long as a control's Enabled property is set to Yes, you can click the control 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 TAB. However, they can still click the command button to choose it.

See Also

AutoTab property, Cycle property, Enabled, Locked properties, TabIndex property.

Tag Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Form section, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Page, Page Break control, Rectangle control, Report, Report section, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Description

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 by 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.

See Also

Name property.

Page 722: Microsoft Access Language

Microsoft Access Language Reference Página 722 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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. This example displays the descriptive text for a text box named txtDescription and a command button named cmdButton on a form.

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 SubSub txtDescription_GotFocus() ' Tag property setting as caption. Me!lblMessage.Caption = Me!txtDescription.TagEnd Sub

Sub txtDescription_LostFocus() Me!lblMessage.Caption = ""End Sub

Sub cmdButton_GotFocus() ' Tag property setting as caption. Me!lblMessage.Caption = Me!cmdButton.TagEnd Sub

Sub cmdButton_LostFocus() Me.lblMessage.Caption = " "End Sub

Terminate Event

Applies To

Module object.

Description

The Terminate event for a class module occurs when all references to an instance of that class are removed from memory.

Note To run code when the Terminate event occurs, you must place that code within the Terminate event procedure in a class module.

Remarks

This event occurs only when you remove a reference to an instance of a class from memory.

See Also

Initialize event.

Page 723: Microsoft Access Language

Microsoft Access Language Reference Página 723 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Terminate Event — Event Procedures

Description

To create the event procedure for the Terminate event, open the class module and click Class in the Object box. Then click Terminate in the Procedure box.

Syntax

Private Sub Class_Terminate( )

Remarks

To remove a reference to an instance of a class from memory, you can set the variable to which that reference is assigned to Nothing. For example, suppose you've created an instance of a class named CustomObject and assigned it to an object variable named obj. When you set obj to Nothing, the reference is removed from memory. Once all references to the instance of the class have been removed from memory, the Terminate event occurs.

A reference to an instance of a class will also be removed from memory when the object variable to which it's assigned goes out of scope. For example, if the variable is defined within a procedure, it will go out of scope when the procedure has finished running. If the variable is defined at the module level in a standard module, it will go out of scope when the code is reset. If all references to an instance of a class are removed in this way, the Terminate event also occurs.

The Terminate event isn't triggered if instances of a class were removed from memory because Microsoft Access terminated abnormally. For example, if your code invokes the Quit method of the Microsoft Access Application object before removing all existing instances of the class from memory, the Terminate event isn't triggered for that class.

See Also

Initialize event, Terminate event.

Example

See the Initialize event — event procedures example.

Text Property

Applies To

Combo Box control, Text Box control.

Description

Page 724: Microsoft Access Language

Microsoft Access Language Reference Página 724 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can use the Text property to set or return the text contained in a text box or in the text box portion of a combo box.

Setting

You can set the Text property to the text you want to display in the control. You can also use the Text property to read the text currently in the control.

You can set or read this property only by using a macro or Visual Basic.

Note To set or return a control's Text property, the control must have the focus, or an error occurs. To move the focus to a control, you can use the SetFocus method or GoToControl action.

Remarks

While the control has the focus, the Text property contains the text data currently in the control; the Value property contains the last saved data for the control. When you move the focus to another control, the control's data is updated, and the Value property is set to this new value. The Text property setting is then unavailable until the control gets the focus again. If you use the Save Record command on the Records menu to save the data in the control without moving the focus, the Text property and Value property settings will be the same.

See Also

Caption property, Name property, Value property.

Example

The following example uses the Text property to enable a Next button named btnNext whenever the user enters text into a text box named txtName. Anytime the text box is empty, the Next button is disabled.

Sub txtName_Change() btnNext.Enabled = Len(Me!txtName.Text & "")<>0End Sub

TextAlign Property

See LabelAlign, TextAlign Properties.

TextHeight Method

Applies To

Report object.

Page 725: Microsoft Access Language

Microsoft Access Language Reference Página 725 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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 has the following arguments.

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 9-point Arial will require a different amount of space than one formatted in 12-point Courier. To determine the current font and font 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 the strexpr argument 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.

See Also

FontName, FontSize properties, Scale method, TextWidth method.

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. Set the OnPrint property of the Detail section to [Event Procedure]. Enter the following code in the report's module, then switch

Argument Description

object The Report object that determines the font and font point size.

strexpr The text string for which the text height will be determined.

Page 726: Microsoft Access Language

Microsoft Access Language Reference Página 726 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 font 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

Applies To

Report object.

Description

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 has the following arguments.

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 9-point Arial will require a different amount of space than one formatted in 12-point Courier. To determine the current font and font 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

Argument Description

object The Report object that determines the font and font point size.

strexpr The text string for which the text width will be determined.

Page 727: Microsoft Access Language

Microsoft Access Language Reference Página 727 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

determine the coordinate system currently in effect for the report.

If the strexpr argument 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.

See Also

FontName, FontSize properties, Scale method, TextHeight method.

Example

See the TextHeight method example.

Timer Event

Applies To

Form.

Description

The Timer event occurs for a form at regular intervals as specified by the form's TimerInterval property.

Remarks

To run a macro or event procedure when this event occurs, set the OnTimer property to the name of the macro or to [Event Procedure].

By running a macro or 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.

See Also

Event properties, Timer function, TimerInterval property.

Timer Event — Event Procedures

Description

Page 728: Microsoft Access Language

Microsoft Access Language Reference Página 728 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

To create an event procedure that runs 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.

See Also

Timer event — macros.

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 the example, add the following event procedure to 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

Description

To run a macro when the Timer event occurs, set the OnTimer 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.

See Also

Timer event — event procedures.

TimerInterval Property

Applies To

Page 729: Microsoft Access Language

Microsoft Access Language Reference Página 729 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Form.

Description

You can use the TimerInterval property to specify the interval, in milliseconds, between Timer events on a form.

Setting

The TimerInterval property setting is a Long Integer value between 0 and 2,147,483,647.

You can set this property by using the form's property sheet, a macro, or Visual Basic.

Note When using Visual Basic, you set the TimerInterval property in the form's Load event.

Remarks

To run Visual Basic code at intervals specified by the TimerInterval property, put the code in the form's Timer event procedure. For example, to requery records every 30 seconds, put the code to requery the records in the form's Timer event procedure, and then set the TimerInterval property to 30000.

See Also

Timer event.

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 = 1000End Sub

Sub Form_Timer() Static intShowPicture As Integer If intShowPicture Then ' Show icon. Me!btnPicture.Picture = "C:\Icons\Flash.ico" Else ' Don't show icon. Me!btnPicture.Picture = "" End If intShowPicture = Not intShowPictureEnd Sub

Toolbar Property

Applies To

Form, Report.

Page 730: Microsoft Access Language

Microsoft Access Language Reference Página 730 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

You can use the Toolbar property to specify the toolbar to use for a form or report. You create these toolbars by using the Customize subcommand of the Toolbars command on the View menu.

Setting

The Toolbar property setting is the name of the custom toolbar you want to display. If you leave the Toolbar property setting blank, Microsoft Access displays the form's or report's built-in (default) toolbar.

You can set the Toolbar property by using the form's or report's property sheet, a macro, or Visual Basic.

In Visual Basic, set this property by using a string expression that's the name of the toolbar you want to display.

To display the built-in toolbar for a form or report by using a macro or Visual Basic, set the Toolbar property to a zero-length string (" ").

Remarks

When you set the Toolbar property, Microsoft Access displays the specified custom toolbar when the form or report is opened. This toolbar is displayed whenever the form or report has the focus.

Top Property

See Left, Top Properties.

TopValues Property

Applies To

Action query, Parameter query, Select query.

Description

You can use the TopValues property to return a specified number of records or a percentage of records that meet the criteria you specify. For example, you might want to return the top 10 values or the top 25 percent of all values in a field.

Note The TopValues 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

Page 731: Microsoft Access Language

Microsoft Access Language Reference Página 731 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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't set this property in code directly. It's set 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 by using the query's property sheet or the Top Values box on the Query Design toolbar.

Note The TopValues property in the query's 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 can type any valid setting in 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 selected 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 has the following sales totals.

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

60,000 Suyama

50,000 Buchanan

Page 732: Microsoft Access Language

Microsoft Access Language Reference Página 732 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Note To return the topmost or bottommost values without displaying duplicate values, set the UniqueValues property in the query's property sheet to Yes.

Example

The following example assigns an SQL string that returns the top 10 most expensive products to the RecordSource property for a form that will display the ten most expensive products.

Dim strGetSQL As StringstrGetSQL = "SELECT TOP 10 Products.[ProductName] " _ & "AS TenMostExpensiveProducts, Products.UnitPrice FROM Products " _ & "ORDER BY Products.[UnitPrice] DESC;"Me.RecordSource = strGetSQL

TransferDatabase Action

Description

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 action has the following arguments.

Sales Salesperson

90,000 Leverling

80,000 Peacock

70,000 Davolio

70,000 King

Page 733: Microsoft Access Language

Microsoft Access Language Reference Página 733 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Action argument

Description

Transfer Type

The type of transfer you want to make. Select Import, Export, or Link in the Transfer Type box 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 box. The default is Microsoft Access.

The database types shown in the Database Type argument depend on how you've 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 and ActiveX Controls option in the dialog box and click the Change Option button, and then select the database type you want to install from the Database Drivers box and click the Change Option button again. Some database drivers are only included in the Office 97 ValuPack (additionally, the ValuPack includes all of the database drivers available from Microsoft Access Setup).

Database Name

The name of the database to import from, export to, or link to. Include the full path. 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 file name in the Source argument (to import or link) or the Destination argument (to export).

Page 734: Microsoft Access Language

Microsoft Access Language Reference Página 734 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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 by pointing to Get External Data on the File menu and clicking Link Tables. Open the table in Design view and view the table properties. The text 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 of 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 file name. Include the file name extension (such as .dbf) in the file name. This is a required argument.

Page 735: Microsoft Access Language

Microsoft Access Language Reference Página 735 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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. 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.

In Microsoft Access 97, if you import a table from another Microsoft Access database that's a linked table in that database, it will still be linked after you import it. That is, the link is imported, not the table itself.

If the database you're accessing requires a password, a dialog box appears when you run the macro. Type the password in this dialog box.

Note You can only import and export data between Microsoft Access and FoxPro version 3.0

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 file name. Include the file name extension (such as .dbf) in the file name. 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 or other object 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.

Page 736: Microsoft Access Language

Microsoft Access Language Reference Página 736 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

databases. You can't link to tables in these FoxPro databases.

The TransferDatabase action is similar to pointing to Get External Data or Save As/Export on the File menu of the Database window and clicking Import or Link Tables. 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 appear 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 pointing to Get External Data on the File menu and clicking Link Tables, then 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 Office folder (the path is C:\Program Files\Microsoft Office\Office). 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.

Note If you query or filter a linked table, the query or filter is case-sensitive.

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

See Also

Connect property ("DAO Language Reference"), CopyObject action, OutputTo action, Save action, SendObject action, TransferDatabase method, TransferSpreadsheet action, TransferText action.

TransferDatabase Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Page 737: Microsoft Access Language

Microsoft Access Language Reference Página 737 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Argument Description

transfertype One of the following intrinsic constants:

acExportacImport (default)acLink

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

databasetype A string expression that's 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's 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:

acFormacMacroacModuleacQueryacReportacTable (default)

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.

Page 738: Microsoft Access Language

Microsoft Access Language Reference Página 738 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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

Note The constant acDefault, which appears in the Auto List Members list for this argument, is invalid for this argument. You must choose one of the constants listed above.

Argument Description

source A string expression that's the name of the object whose data you want to import, export, or link.

destination A string expression that's 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.

Page 739: Microsoft Access Language

Microsoft Access Language Reference Página 739 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Note Although you can use the TransferDatabase method in Visual Basic to link tables, it's recommended that you use Data Access Objects (DAO) instead. To create a link by using DAO, use the Connect property for the TableDef object.

See Also

Connect property ("DAO Language Reference"), CopyObject method, CreateTableDef method ("DAO Language Reference"), DoCmd object, RefreshLink method ("DAO Language Reference"), Save method, TableDef object ("DAO Language Reference"), TransferDatabase action, TransferSpreadsheet method, TransferText method.

Example

The following 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"

The next 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 Action

Description

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. You can also link to data in a Lotus 1-2-3 spreadsheet file, but this data is read-only in Microsoft Access.

This argument is available only in Visual Basic.

Page 740: Microsoft Access Language

Microsoft Access Language Reference Página 740 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The TransferSpreadsheet action has 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 box 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 3.

Notes

l If you want to import, export, or link spreadsheet data to or from Lotus 1-2-3 files, you must install the Lotus 1-2-3 driver from the Office 97 ValuPack.

l You can import from and link (read-only) to Lotus .WK4 files, but you can't export Microsoft Access data to this spreadsheet format. Microsoft Access also no longer supports importing, exporting, or linking data from Lotus .WKS or Microsoft Excel version 2.0 spreadsheets with this action. If you want to import from or link to spreadsheet data in Microsoft Excel version 2.0 or Lotus .WKS format, convert the spreadsheet data to a later version of Microsoft Excel or Lotus 1-2-3 before importing or linking the data into Microsoft Access.

Page 741: Microsoft Access Language

Microsoft Access Language Reference Página 741 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

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.

Action argument

Description

In Microsoft Access 97, you can't use an SQL statement to specify data to export when you are using 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 argument.

File Name 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 file name 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, 7.0, or Excel 97 workbook. In that case, Microsoft Access copies the exported data to the next available new worksheet in the workbook.

Page 742: Microsoft Access Language

Microsoft Access Language Reference Página 742 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can export the data in Microsoft Access select queries to spreadsheets. 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

If you are importing from or linking to a Microsoft Excel version 5.0, 7.0, or Excel 97 spreadsheet, you can specify a particular worksheet by using the Range argument.

Has Field Names

Specifies whether the first row of the spreadsheet contains the names of the fields. If you select 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 select No, Microsoft Access treats the first row as a normal row of data. The default is No.

When you export a Microsoft Access table or select query to a spreadsheet, the field names are inserted into the first row of the spreadsheet no matter what you select in this argument.

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 (note that the A1..E25 syntax no longer works in Microsoft Access 97). If you are importing from or linking to a Microsoft Excel version 5.0, 7.0, or Excel 97 worksheet, you can prefix the range with the name of the worksheet and an exclamation point; for example, Budget!A1:C7.

Note When you export to a spreadsheet, you must leave this argument blank. If you enter a range, the export will fail.

Page 743: Microsoft Access Language

Microsoft Access Language Reference Página 743 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 pointing to Get External Data or Save As/Export on the File menu of the Database window and clicking Import or Link Tables. 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.

Note If you query or filter a linked spreadsheet, the query or filter is case-sensitive.

If you link to an Excel spreadsheet open in Edit mode, Access will wait until the Excel spreadsheet is out of Edit mode before completing the link; there's no time-out.

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

See Also

OutputTo action, SendObject action, TransferDatabase action, TransferSpreadsheet method, TransferText action.

TransferSpreadsheet Method

Applies To

DoCmd object.

Description

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 has the following arguments.

Argument Description

transfertype One of the following intrinsic constants:

Page 744: Microsoft Access Language

Microsoft Access Language Reference Página 744 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

acImport (default)acExportacLink

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

Argument Description

spreadsheettype One of the following intrinsic constants, or equivalent numeric settings:

0 acSpreadsheetTypeExcel3 (default)6 acSpreadsheetTypeExcel45 acSpreadsheetTypeExcel55 acSpreadsheetTypeExcel78 acSpreadsheetTypeExcel972 acSpreadsheetTypeLotusWK13 acSpreadsheetTypeLotusWK37 acSpreadsheetTypeLotusWK44 acSpreadsheetTypeLotusWJ2 — Japanese version only

Note You can link to data in a Lotus 1-2-3 spreadsheet file, but this data is read-only in Microsoft Access. You can import from and link (read-only) to Lotus .WK4 files, but you can't export Microsoft Access data to this spreadsheet format. Microsoft Access also no longer supports importing, exporting, or linking data from Lotus .WKS or Microsoft Excel version 2.0 spreadsheets by using this method.

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

Page 745: Microsoft Access Language

Microsoft Access Language Reference Página 745 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Note Although you can use the TransferSpreadsheet method in Visual Basic to link to spreadsheet data, it's recommended that you use Data Access Objects (DAO) instead. To create a link by using DAO, use the Connect property for the TableDef object.

See Also

tablename A string expression that's 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's 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 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.

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 no matter what you enter for this argument.

range A string expression that's 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.

When you export to a spreadsheet, you must leave this argument blank. If you enter a range, the export will fail.

Page 746: Microsoft Access Language

Microsoft Access Language Reference Página 746 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Connect property ("DAO Language Reference"), CreateTableDef method ("DAO Language Reference"), DoCmd object, OutputTo method, RefreshLink method ("DAO Language Reference"), SendObject method, TableDef object ("DAO Language Reference"), TransferDatabase method, TransferSpreadsheet action, TransferText method.

Example

The following 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 Action

Description

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 the text data with Microsoft Access while still allowing complete access to the data from your word processing program. You can also import from, export to, and link to a table or list in an HTML file (*.html).

Note If you link to data in a text file or an HTML file, the data is read-only in Microsoft Access.

Setting

The TransferText action has 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 or HTML files. You can also export data to a Microsoft Word mail merge data file, which you can then use with the Microsoft Word mail merge feature to create merged documents such as form letters and mailing labels.

Page 747: Microsoft Access Language

Microsoft Access Language Reference Página 747 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Select Import Delimited, Import Fixed Width, Import HTML, Export Delimited, Export Fixed Width, Export HTML, Export Word for Windows Merge, Link Delimited, Link Fixed Width, or Link HTML in the Transfer Type box in the Action Arguments section of the Macro window. The default is Import Delimited.

Action argument

Description

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 Import Text Wizard, Export Text 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 appears. 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

Page 748: Microsoft Access Language

Microsoft Access Language Reference Página 748 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

name for this argument when you export these types of files. You can use import/export specifications with HTML files, but the only part of the specification that applies is the specification for data type formatting.

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, Import Fixed Width, or Import HTML 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.

In Microsoft Access 97, you can't use an SQL statement to specify data to export when you are using the TransferText 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 argument.

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 file name is the same as the name of an existing text file, Microsoft Access replaces the existing text file.

If you want to import or link a particular table or list in an HTML file, you can use the HTML Table Name argument.

Page 749: Microsoft Access Language

Microsoft Access Language Reference Página 749 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

(continued)

Has Field Names

Specifies whether the first row of the text file contains the names of the fields. If you select 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 select No, Microsoft Access treats the first row as a normal row of data. The default is No.

Microsoft Access ignores this argument for Microsoft Word for Windows mail merge data files because the first row must contain the field names.

When you export a Microsoft Access table or select query 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've selected Yes for this argument.

If you are importing or linking a fixed-width text file and select 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 select Yes for this argument, Microsoft Access inserts the field names into the first row of the text file with this delimiter.

HTML Table Name

The name of the table or list in the HTML file that you want to import or link. This argument is ignored unless the Transfer Type argument is set to Import HTML or Link HTML. If you leave this argument blank, the first table or list in the HTML file is imported or linked.

Page 750: Microsoft Access Language

Microsoft Access Language Reference Página 750 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

You can export the data in Microsoft Access select queries to text files. 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 pointing to Get External Data or Save As/Export on the File menu of the Database window and clicking Import or Link Tables. 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 or an HTML file, a wizard prompts you to select the name of the 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.

Note If you query or filter a linked text file, the query or filter is case-sensitive.

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

See Also

OutputTo action, SendObject action, TransferDatabase action, TransferSpreadsheet action, TransferText method.

TransferText Method

The table or list name in the HTML file is determined by the text specified by the <CAPTION> tag, if there's a <CAPTION> tag. If there's no <CAPTION> tag, the name is determined by the text specified by the <TITLE> tag. If more than one table or list has the same name, Microsoft Access distinguishes them by adding a number to the end of each name; for example, Employees1 and Employees2.

Page 751: Microsoft Access Language

Microsoft Access Language Reference Página 751 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

DoCmd object.

Description

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][, HTMLtablename]

The TransferText method has the following arguments.

(continued)

Argument Description

transfertype One of the following intrinsic constants:

acExportDelimacExportFixedacExportHTMLacExportMergeacImportDelim (default)acImportFixedacImportHTMLacLinkDelimacLinkFixedacLinkHTML

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

Note You can link to data in a text file or HTML file, but this data is read-only in Microsoft Access.

Page 752: Microsoft Access Language

Microsoft Access Language Reference Página 752 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

specificationname A string expression that's the name of an import or export specification you've created and saved in the current database.

This argument is required for fixed-width text files. For delimited text files and Microsoft Word mail merge data files, you can leave this argument blank to select the default import/export specifications.

tablename A string expression that's 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's 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 Microsoft Word mail merge data files, which must always contain the field names in the first row.

HTMLtablename A string expression that's the name of the table or list in the HTML file that you want to import or link. This argument is ignored unless the transfertype argument is set to acImportHTML or acLinkHTML. If you leave this argument blank, the first table or list in the HTML file is imported or linked.

Page 753: Microsoft Access Language

Microsoft Access Language Reference Página 753 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

Note Although you can use the TransferText method in Visual Basic to link to text data, it's recommended that you use Data Access Objects (DAO) instead. To create a link by using DAO, use the Connect property for the TableDef object.

See Also

Connect property ("DAO Language Reference"), CreateTableDef method ("DAO Language Reference"), DoCmd object, OutputTo method, RefreshLink method ("DAO Language Reference"), SendObject method, TableDef object ("DAO Language Reference"), TransferDatabase method, TransferSpreadsheet method, TransferText action.

Example

The following example exports the data from the Microsoft Access table External Report to the delimited text file April.doc by using the specification Standard Output:

DoCmd.TransferText acExportDelim, "Standard Output", _ "External Report", "C:\Txtfiles\April.doc"

Transparent Property

Applies To

Command Button control.

Description

You can use the Transparent property to specify whether a command button is solid or transparent.

The name of the table or list in the HTML file is determined by the text specified by the <CAPTION> tag, if there's a <CAPTION> tag. If there's no <CAPTION> tag, the name is determined by the text specified by the <TITLE> tag. If more than one table or list has the same name, Microsoft Access distinguishes them by adding a number to the end of each table or list name; for example, Employees1 and Employees2.

Page 754: Microsoft Access Language

Microsoft Access Language Reference Página 754 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Tip Use the BackStyle property to make other controls solid or transparent.

Setting

The Transparent property uses the following settings.

You can set this property by using 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 control and run various macros or Visual Basic event procedures depending on 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.

See Also

BackColor property, BackStyle property, DisplayWhen property, Enabled, Locked properties, Visible property.

TripleState Property

Applies To

Check Box control, Option Button control, Toggle Button control.

Description

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 doesn't apply to the specified controls when they are used inside an option group control.

Setting Description Visual Basic

Yes The button is transparent. True (–1)

No (Default) The button is solid. False (0)

Page 755: Microsoft Access Language

Microsoft Access Language Reference Página 755 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The TripleState property uses the following settings.

You can set the TripleState property by using a control's property sheet, a macro, or Visual Basic.

This property can be set in any view.

Type Property

Applies To

Module object.

Description

The Type property indicates whether a module is a standard module or a class module.

Setting

The Type property is available only by using Visual Basic and is read-only.

If the module is a standard module, the value of the Type property is acStandardModule or 0. If the module is a class module, the value of the Type property is acClassModule or 1.

Example

The following example determines whether a Module object represents a standard module or a class module:

Setting Description Visual Basic

Yes The control will cycle through states for Yes, No, and Null values. The control appears dimmed (grayed) when its Value property is set to Null.

True (–1)

No (Default) The control will cycle through states for Yes and No values. Null values display as if they were No values.

False (0)

Page 756: Microsoft Access Language

Microsoft Access Language Reference Página 756 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Function CheckModuleType(strModuleName As String) As Integer Dim mdl As Module

' Open module to include in Modules collection. DoCmd.OpenModule strModuleName ' Return reference to Module object. Set mdl = Modules(strModuleName) ' Check Type property. If mdl.Type = acClassModule Then ' Insert comment. mdl.InsertLines 1, "' Class module." CheckModuleType = acClassModule Else ' Insert comment. mdl.InsertLines 1, "' Standard module." CheckModuleType = acStandardModule End IfEnd Function

Undo Method

Applies To

Check Box control, Combo Box control, Control object, Form object, List Box control, Text Box control.

Description

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 has the following argument.

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 in a control's Change event.

Argument Description

object A Form object or a Control object.

Page 757: Microsoft Access Language

Microsoft Access Language Reference Página 757 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

The Undo method offers an alternative to using the SendKeys statement to send the value of the ESC key in an event procedure.

See Also

OldValue property.

Example

The following example shows how you can use the Undo method within a control's Change event procedure to force a field named LastName to reset to its original value, if it changed.

Private Sub LastName_Change() Me!LastName.UndoEnd 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.UndoEnd Sub

Unique Property

Applies To

Index.

Description

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)

Page 758: Microsoft Access Language

Microsoft Access Language Reference Página 758 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property in the Indexes window of table Design view or by using Visual Basic.

Note To access the Unique property of an index by using Visual Basic, use the DAO Unique property.

Remarks

A key index optimizes 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.

See Also

IgnoreNulls property, Index object ("DAO Language Reference"), Indexes collection ("DAO Language Reference"), Primary property, Primary property ("DAO Language Reference").

Example

See the IgnoreNulls property example.

UniqueRecords Property

Applies To

Action query, Select query.

Description

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 append and make-table action queries and select queries.

Setting

The UniqueRecords property uses the following settings.

Setting Description

Yes Doesn't return duplicate records.

Page 759: Microsoft Access Language

Microsoft Access Language Reference Página 759 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set the UniqueRecords property in the query's property sheet or in SQL view of the Query window.

Note You set this property when you create a new query by 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.

See Also

ALL, DISTINCT ROW, TOP predicates ("SQL Language Reference"), UniqueValues 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

No (Default) Returns duplicate records.

Company name Customer ID

Ernst Handel ERNSH

Familia Arquibaldo FAMIA

FISSA Fabrica Inter. Salchichas S.A.

FISSA

Page 760: Microsoft Access Language

Microsoft Access Language Reference Página 760 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Orders Table

The following SQL statement returns the customer names in the following table:

SELECT DISTINCTROW Customers.CompanyName, Customers.CustomerIDFROM Customers INNER JOIN OrdersON Customers.CustomerID = Orders.CustomerID;

UniqueValues Property

Applies To

Folies gourmandes FOLIG

Customer ID Order ID

ERNSH 10698

FAMIA 10512

FAMIA 10725

FOLIG 10763

FOLIG 10408

Customers returned Customer ID

Ernst Handel ERNSH

Familia Arquibaldo FAMIA

Folies gourmandes FOLIG

Page 761: Microsoft Access Language

Microsoft Access Language Reference Página 761 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Action query, Select query.

Description

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 append and make-table action queries and select queries.

Setting

The UniqueValues property uses the following settings.

You can set the UniqueValues property in the query's property sheet or in SQL view of the Query window.

Note You can set this property when you create a new query by 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.

See Also

ALL, DISTINCT, DISTINCTROW, TOP predicates ("SQL Language Reference"), UniqueRecords property.

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.

Page 762: Microsoft Access Language

Microsoft Access Language Reference Página 762 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

This SQL statement returns the countries in the following table:

SELECT DISTINCT Customers.CountryFROM Customers;

Country Company name

Brazil Familia Arquibaldo

Brazil Gourmet Lanchonetes

Brazil Hanari Carnes

France Du monde entier

France Folies gourmandes

Germany Frankenversand

Ireland Hungry Owl All-Night Grocers

Countries returned

Brazil

France

Germany

Page 763: Microsoft Access Language

Microsoft Access Language Reference Página 763 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Unload Event

See Load, Unload Events.

Updated Event

Applies To

ActiveX control, Bound Object Frame control, Unbound Object Frame control.

Description

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

To run a macro or event procedure when this event occurs, set the OnUpdated property to the name of the macro or to [Event Procedure].

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.

Notes

l 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.

l The Calendar control included with Microsoft Access 97 no longer supports the Updated event. If you convert a database that includes the Calendar control from a previous version of Microsoft Access to Microsoft Access 97, you should move any code in the Updated event of the Calendar control to the AfterUpdate event.

See Also

Ireland

Page 764: Microsoft Access Language

Microsoft Access Language Reference Página 764 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Action property, BeforeUpdate, AfterUpdate events, Class property, Event properties, OLEType property, OLETypeAllowed property, UpdateOptions property.

Updated Event — Event Procedures

Description

To create an event procedure that runs when the Updated event occurs, set the OnUpdated property to [Event Procedure], and click the Build button.

Syntax

Private Sub controlname_Updated(Code As Integer)

The Updated event procedure has the following arguments.

Argument Description

controlname The name of the control whose Updated event procedure you want to run.

Code The setting indicates how the OLE object was updated. The Code argument can be one of the following intrinsic constants:

Constant Description

acOLEChanged Indicates that the object's data has changed.

Page 765: Microsoft Access Language

Microsoft Access Language Reference Página 765 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

To see if an object's data has been changed since it was last saved, set a public variable in the Updated event procedure indicating that the object needs to be saved. When you save the OLE object, reset the variable.

You can't cancel the Updated event.

See Also

Updated event — macros.

Updated Event — Macros

Description

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.

acOLESaved Indicates that the object's data has been saved by the application that created the object. This usually occurs when the user clicks 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.

Page 766: Microsoft Access Language

Microsoft Access Language Reference Página 766 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can't use the CancelEvent action in an Updated macro.

See Also

Updated event — event procedures.

UpdateOptions Property

Applies To

Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

You can use the UpdateOptions property to specify how a linked OLE object is updated.

Setting

The UpdateOptions property uses the following settings.

You can set the UpdateOptions property in a property sheet, in a macro, or by using Visual Basic. You can set the default for this property by using a control's default control style or the DefaultControl method in Visual Basic.

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

Setting Description Visual Basic

Automatic (Default) Updates the object each time the linked data changes.

acOLEUpdateAutomatic (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.

acOLEUpdateManual (2)

Page 767: Microsoft Access Language

Microsoft Access Language Reference Página 767 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 don't occur based on the setting of the Refresh Interval box on 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.

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 = acOLEUpdateManualOLE1.Action = acOLEUpdate

See Also

Action property, Class property, OLEType property, OLETypeAllowed property, Updated event.

UserControl Property

Applies To

Application object.

Description

You can use the UserControl property to determine whether the current Microsoft Access application was started by the user or by another application with Automation, formerly called 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 with Automation.

Page 768: Microsoft Access Language

Microsoft Access Language Reference Página 768 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can determine the UserControl property setting only by 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 isn't possible to set the Visible property of the object to False.

When an Application object is created by using Automation, the Visible and UserControl properties of the object are both set to False.

See Also

Application object, Visible property (Application object).

UseTransaction Property

Applies To

Action query, QueryDef object.

Description

You can use the UseTransaction property to specify or determine whether an action query runs as a single transaction. In some situations, setting this property to No can make queries run much faster.

Setting

The UseTransaction property uses the following settings.

You can set the UseTransaction property by using the query's property sheet or Visual Basic. To set this property with Visual Basic, you must first add it to a QueryDef object's Properties collection by using the CreateProperty method.

Setting Description Visual Basic

Yes (Default) The query runs as a single transaction.

True (–1)

No The query doesn't run as a single transaction.

False (0)

Page 769: Microsoft Access Language

Microsoft Access Language Reference Página 769 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Remarks

When a make-table, delete, append, or update query has its UseTransaction property set to Yes, the Microsoft Jet database engine stores the returned records in a cache and, if necessary, stores the results in a temporary database on disk. When the query has finished, the Jet database engine reads the records from the temporary database and writes them back to the original database.

You may get substantial performance benefits by setting the UseTransaction property to No in the right circumstances. When the UseTransaction property is set to No, the user will never encounter problems associated with too many lock requests. In addition, the Jet database engine doesn't store query results in a temporary database, thereby achieving a substantial performance increase.

If there is a large number of records that must be written to the temporary database, performance may suffer as a result of running an action query as a single transaction. In addition, when running delete or update queries in a shared database, a large number of lock requests are generated. This may cause performance to suffer and in some Network Operating Systems like Netware it can cause the query to fail when the lock requests exceed 10,000.

If a transaction can't be completed, an error message appears and you have the option of saving any changes.

When the UseTransaction property is set to No, the only way to roll back an entire transaction is to use the DAO RollBack method in Visual Basic.

See Also

BeginTrans, CommitTrans, Rollback methods, CreateProperty method ("DAO Language Reference"), FailOnError property.

ValidationRule, ValidationText Properties

Applies To

Check Box control, Combo Box control, List Box control, Option Button control, Option Group control, Table field, Text Box control, Toggle Button control.

Description

You can use the ValidationRule property to specify requirements for data entered into a record, field, or control. When data is entered that violates the ValidationRule setting, you can use the ValidationText property to specify the message to be displayed to the user.

Note The ValidationRule and ValidationText properties don't 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

Page 770: Microsoft Access Language

Microsoft Access Language Reference Página 770 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Enter an expression for the ValidationRule property setting and text for the ValidationText property setting. The maximum length for the ValidationRule property setting is 2048 characters. The maximum length for the ValidationText property setting is 255 characters.

For controls, you can set the ValidationRule property to any valid expression. For field and record validation rules, the expression can't contain user-defined functions, domain aggregate 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 by using:

l The Field Properties section of table Design view (for a field validation rule).l The property sheet for a table by clicking Properties on the View menu in table Design view

(for a record validation rule).l The property sheet for a control on a form.l A macro or Visual Basic. In Visual Basic, use a string expression to set these properties.

For table fields and records, you can also set these properties in Visual Basic by using the DAO 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 rules that are more specific by 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 value in the employee's StartDate 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:

l Validation rules you set for fields and controls are applied when you edit the data and the focus leaves the field or control.

l Validation rules for records are applied when you move to another record.l 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.

Page 771: Microsoft Access Language

Microsoft Access Language Reference Página 771 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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" and make sure the Required property is set to No.

You can't set field or record validation rules for tables created outside Microsoft Access (for example, dBASE, Paradox, or SQL Server). For these kinds of tables, you can create validation rules for controls only.

See Also

AllowZeroLength property, Required property, ValidationRule property ("DAO Language Reference"), ValidationText property ("DAO Language Reference").

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 by using the SetFieldValidation function.

Dim strTblName As String, strFldName As StringDim strValidRule As StringDim strValidText As String, intX As Integer

strTblName = "Customers"strFldName = "Age"

ValidationRule property ValidationText property

<> 0 Entry must be a nonzero 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/96# And <#1/1/97# Entry must be a date in 1996.

DLookup("CustomerID", "Customers", "CustomerID = Forms!Customers!CustomerID") Is Null

Entry must be a unique CustomerID (domain aggregate functions are allowed only for form-level validation).

Page 772: Microsoft Access Language

Microsoft Access Language Reference Página 772 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 dbs As Database, tdf As TableDef, fld As Field

Set dbs = CurrentDb Set tdf = dbs.TableDefs(strTblName) Set fld = tdf.Fields(strFldName) fld.ValidationRule = strValidRule fld.ValidationText = strValidTextEnd 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 StringDim strValidText As StringDim 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 dbs As Database, tdf As TableDef

Set dbs = CurrentDb Set tdf = dbs.TableDefs(strTblName) tdf.ValidationRule = strValidRule tdf.ValidationText = strValidTextEnd Function

Value Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, List Box control, Option Button control, Option Group control, Tab control, Text Box control, Toggle Button control.

Description

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.

l Check box, option button, and toggle button controls. Determines or specifies whether or not the control is selected.

l Combo box, list box, and option group controls. Determines or specifies which value or option in the control is selected.

l Text box controls. Determines or specifies the text in the text box.l Tab control. Determines or specifies the selected Page object.

Page 773: Microsoft Access Language

Microsoft Access Language Reference Página 773 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Setting

The Value property uses the following setting depending on the specified control.

(continued)

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 [The 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

False

Option group

[The OptionValue property setting]

The OptionValue property setting for the selected control in the group.

Page 774: Microsoft Access Language

Microsoft Access Language Reference Página 774 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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 current while the control has the focus.

Toggle button

True

False

The toggle button is pressed in.

The toggle button isn't pressed in.

True

False

Tab control

[An Integer value representing the index number of the currently selected Page object]

The Value property of a tab control contains the index number of the current Page object. There is one Page object for each tab in a tab control. The first Page object always has an index number of 0, the second has an index number of 1, and so on.

Bound object frame or chart control

The Value property for a bound object frame or a bound chart control is set to the value of the field that the control is bound to. Since these fields normally contain OLE objects or chart objects, which are stored as binary data, this

Page 775: Microsoft Access Language

Microsoft Access Language Reference Página 775 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

You can set this property by using 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. In the following example, because the default value of the 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.

Forms!frmCustomers!txtLastName = "Smith"

This means that the following two statements are equivalent.

Forms!frmCustomers!optCreditApproved.Value = TrueForms!frmCustomers!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.

See Also

DefaultValue property, OldValue property, OptionValue property, Text 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 IfEnd Sub

value is usually meaningless.

ActiveX control

Some ActiveX controls support the Value property. For example, the Value property setting for a Calendar control is the currently selected date in the control. For more information, see the documentation for each ActiveX control.

Page 776: Microsoft Access Language

Microsoft Access Language Reference Página 776 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Verb Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Unbound Object Frame control.

Description

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. 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 by using the control's property sheet, a macro, or Visual Basic. You can set the default for this property by using the default control style or the DefaultControl method in Visual Basic.

If you don't use the ObjectVerbs property to identify a specific verb, 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.

With some applications' objects, you can use these additional values.

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 was used to create the object.

Page 777: Microsoft Access Language

Microsoft Access Language Reference Página 777 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

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.

See Also

Action property, AutoActivate property, ObjectVerbs property, ObjectVerbsCount property.

ViewsAllowed Property

See DefaultView, ViewsAllowed Properties.

Visible Property

Applies To

ActiveX control, Bound Object Frame control, Chart control, Check Box control, Combo Box control, Command Button control, Form, Form section, Image control, Label control, Line control, List Box control, Option Button control, Option Group control, Page, Page Break control, Rectangle control, Report, Report section, Subform/Subreport control, Tab control, Text Box control, Toggle Button control, Unbound Object Frame control.

Constant Value Description

acOLEVerbInPlaceUIActivate –4 Activates the object for editing within the control. The menus and toolbars of the OLE server become available in the OLE container.

acOLEVerbInPlaceActivate –5 Activates the object within the control. The menus and toolbars of the OLE server aren't available in the OLE container.

Page 778: Microsoft Access Language

Microsoft Access Language Reference Página 778 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Description

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.

You can set this property by 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 by using a macro or Visual Basic.

For controls, you can set the default for this property by using the default control style or the DefaultControl method in Visual Basic.

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 or report by including the property in a macro or event procedure 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 by using Visual Basic.

See Also

Current event, DisplayWhen property, Format event, Transparent property, Visible property (Application object).

Setting Description Visual Basic

Yes (Default) The object is visible.

True (–1)

No The object is not visible. False (0)

Page 779: Microsoft Access Language

Microsoft Access Language Reference Página 779 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Visible Property (Application Object)

Applies To

Application object.

Description

You can use the Visible property of the Application object to specify or determine whether a Microsoft Access application is minimized.

Setting

The Visible property uses the following settings.

You can set the Visible property of the Application object only by using Visual Basic. You can set the default for this property by using a control's default control style or the DefaultControl method in 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 isn't possible to set the Visible property of the object to False.

When an Application object is created by using Automation (formerly called OLE Automation), the Visible and UserControl properties of the object are both set to False.

Note When the Visible property of the Application object is set to False, the application is minimized but isn't hidden from the user.

See Also

Application object, UserControl property, Visible property.

WhatsThisButton Property

Setting Description

True (–1) The application is visible.

False (0) The application isn't visible.

Page 780: Microsoft Access Language

Microsoft Access Language Reference Página 780 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Applies To

Form.

Description

You can use the WhatsThisButton property to specify whether a What's This button is added to a form's title bar.

Note You can't display the What's 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.

You can set the WhatsThisButton property by using the form's property sheet, a macro, or Visual Basic.

This property can be set only in form Design view.

Remarks

Clicking the What's This button on the title bar of a form causes the question-mark mouse pointer to appear. With the question-mark 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.

See Also

ControlTipText property, HelpContextID, HelpFile properties, MinMaxButtons property.

Width Property

Setting Description Visual Basic

Yes A What's This button appears on the title bar.

True (–1)

No (Default) A What's This button doesn't appear on the title bar.

False (0)

Page 781: Microsoft Access Language

Microsoft Access Language Reference Página 781 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

See Height, Width Properties.

WillContinue Property

Applies To

Report.

Description

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.

You can get the value of the WillContinue property by using a macro or Visual Basic.

Remarks

You can use this 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.

See Also

HasContinued property.

WindowHeight, WindowWidth Properties

Applies To

Value Description

True (–1) The current section continues on the following page.

False (0) The current section doesn't continue on the following page.

Page 782: Microsoft Access Language

Microsoft Access Language Reference Página 782 de 782

file://C:\WINDOWS\TEMP\~hh12D4.htm 25/11/01

Form.

Description

You can use these properties to return the height and width of a form in twips.

Setting

The WindowHeight and WindowWidth property settings are Integer values.

These property settings are read-only and are available only by using 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.

See Also

CurrentSectionLeft, CurrentSectionTop properties, Height, Width properties, InsideHeight, InsideWidth properties, Left, Top properties.